Baba
Baba

Reputation: 2229

Creating a select all checkbox functionality in a component

I have 2 components which are componentA and componentB.

componentA - Parent
    -Has one checkbox(selectall)
componentB - Children
    -Has many checkboxes on each row

I want a situation where when I check the parent checkbox all the children checkboxes are checked and when I uncheck one of the children the parent is unchecked.

Kindly give some direction on how to do this. I know I have to create a state. I want to use hooks and functional component.

Upvotes: 0

Views: 4118

Answers (2)

Pradeep Nair
Pradeep Nair

Reputation: 34

There are multiple ways of achieving this, One easiest way is create a parent component as follows and send the state value as props to children props

function Parent() {
  const [allSelected, setAllSelected] = useState(false)

 function handleChange(e) {
  setAllSelected(!allSelected)
 }

return (
    <div className="App">
      <input type="checkbox" name="isAllSelected" onChange={handleChange} checked={allSelected}/> Select all
      <CheckboxList isSelected={allSelected}/>
    </div>
  );
}
function CheckboxList(props) {
  return (
    <div className="App">
      <label>
        <input type="checkbox" name="1" checked={props.isSelected}/> 
        1
      </label>
      <label>
        <input type="checkbox" name="2"  checked={props.isSelected}/> 
        2
      </label>
    </div>
  );
}

Upvotes: 1

WebbH
WebbH

Reputation: 2422

Another way would be to have the selectAll onChange event change the value of the all the other boxes

const App = () =>{
  const [allBox, changeAllBox] = useState(false);
  const [testOne, changeTestOne] = useState(false);
  const [testTwo, changeTestTwo] = useState(false);
  const [testThree, changeTestThree] = useState(false);
  const selectAll = () =>{
    const newVal = allBox ? false : true;
    changeTestOne(newVal);
    changeTestTwo(newVal);
    changeTestThree(newVal);
    changeAllBox(newVal);
  }
  const changeValue = (e) =>{
    const number = e.currentTarget.id;
    console.log(number)
    switch(number){
      case '1':
        changeTestOne(!testOne)
        break;
      case '2':
        changeTestTwo(!testTwo)
        break;
      case '3':
        changeTestThree(!testThree)
        break;
    }
  }
  return(
    <div>
      <label htmlFor = 'all'>Select All</label>
      <input id = 'all' type = 'checkbox' onChange = {selectAll} checked = {allBox} />
      <ChildCheck label = '1' id ='1' checked = {testOne} onChange = {changeValue} />
      <ChildCheck label = '2' id = '2' checked = {testTwo} onChange = {changeValue}/>
      <ChildCheck label = '3' id = '3' checked = {testThree} onChange = {changeValue}/>
    </div>
 )
}

Upvotes: 0

Related Questions