jeudi 28 novembre 2019

How to control the state of multiple checkboxes in child component by the parent in react?

I have multiple check-boxes which are dynamic. These check boxes are placed (assume) in "B" component. I have managed the state of these check boxes in "A" component which is the parent of "B". When one or all the check boxes are clicked I want to render a div

expected result : render div if one or all the check boxes are clicked. If none is selected the div should be hidden. Basically the div should be visible even if a single checkbox is checked.

current result : When one check box is clicked the the div gets rendered but if another checkbox is selected the div disappears.

Here's my A component (Parent)

const A = () => {
   const [isChecked, setIsChecked] = useState(false) // state that holds state of check boxes 

   return (
      {isChecked ? <div>Some Content..</div> : null} // rendering the div according to the state of the checkboxes

      <Child isChecked={isChecked} setIsChecked={setIsChecked} />
  ) 
}

Code of Child Component

 const Child = props => {

        return (
           {checkBoxList.map((box, index) => (
              <CustomCheckBox
                 key={index}
                 name={`check-box-${index}`}  // to uniquely identify each check box 
                 isChecked={props.isChecked}
                 setIsChecked={props.setIsChecked} />
           ))}
        )
    }

CustomCheckBox component :

 const CustomCheckBox = props => {

      const onChangeHandler = (event) => {
         props.isChecked ? props.setIsChecked(false) : props.setIsChecked(true)
      }

      return <input name={props.name} type="checkBox" onChange={onChangeHandler} />;
 };

  CustomCheckBox.propTypes = {
    name: string
  }

I'm aware that the parent component state is only capable of handling a single check box right now.

The reason for the current result is because of the condition that I have included onChangeHandler function.

  props.isChecked ? props.setIsChecked(false) : props.setIsChecked(true)

I'm confused about how to handle the state of multiple check boxes in the above stated scenario using a single handler function !




Aucun commentaire:

Enregistrer un commentaire