Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  118] [ 3]  / answers: 1 / hits: 23527  / 5 Years ago, wed, february 6, 2019, 12:00:00

I am trying to implement select/unselect all functionality in reactJs but couldn't make it happen.



I have made select/unselect all main header checkbox functional and the single elements can also be selected or unselected.



My work link: Edit



import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class Box extends Component{
constructor(props){
super(props);
this.state = {
allChecked: false,
list: [
{id:1, name: item1, isChecked: false},
{id:2, name: item2, isChecked: false},
{id:3, name: item3, isChecked: false},
],
};
}

handleChange = (e) => {
let list = this.state.list;
let allChecked = this.state.allChecked;
if(e.target.value === checkAll){
list.forEach(item => {
item.isChecked = e.target.checked;
allChecked = e.target.checked;
});
}
else{
list.find( item => item.name === e.target.name).isChecked = e.target.checked;
}
this.setState({list:list, allChecked: allChecked});
}

renderList = () => {
return this.state.list.map(item =>
<div>
<input key={item.id} type=checkbox name={item.name} value={item.name} checked={item.isChecked} onChange={this.handleChange} />
<label>{item.name}</label>
</div>
)
}
render(){
return(
<div>
<input type=checkbox
value=checkAll
checked={this.state.allChecked}
onChange={this.handleChange} />Check all
<br/>
{this.renderList()}
</div>
);
}
}

ReactDOM.render(<Box/>, document.getElementById('root'));


To be straight forward, i want this (https://jsfiddle.net/52uny55w/) type of functionality using the plain Javascript but not with the jquery for some reasons.


More From » reactjs

 Answers
1

I have solved the problem at https://codesandbox.io/s/vvxpny4xq3



  handleChange = e => {
let itemName = e.target.name;
let checked = e.target.checked;
this.setState(prevState => {
let { list, allChecked } = prevState;
if (itemName === checkAll) {
allChecked = checked;
list = list.map(item => ({ ...item, isChecked: checked }));
} else {
list = list.map(item =>
item.name === itemName ? { ...item, isChecked: checked } : item
);
allChecked = list.every(item => item.isChecked);
}
return { list, allChecked };
});
};


A few things to note.



1) I have updated the checkAll button to have a name property to ensure consistency



2) If modifying the existing state, use the new functional syntax



3) Destructure the objects and do not mutate them in place if possible. You could use map instead of forEach and use spread operator to modify the object without mutating.


[#52648] Thursday, January 31, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tylerdamiena

Total Points: 139
Total Questions: 90
Total Answers: 118

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;