Home > Mobile >  How context API with components made by map function
How context API with components made by map function

Time:10-11

I have a nested component with checkboxes Main->Nested->Nested->maps many components with check boxes(hope it is clear what I mean) I have a context in Main and a state in which I want to keep information about checkboxes states

    interface ICartContext {
        isChecked:boolean;
        setChecked:()=>void;
    }
    const [isChecked, setChecked] = useState(false);

  const state = {
    isChecked:isChecked,
    setExtraChecked:()=>{setExtraChecked(true)} // problem
}

In my component with checkbox I use this state

         <Checkbox 
             checked = {context.isChecked}
             checkedIcon={<CheckIcon/>}
             onChange ={(e)=>{context.setExtraChecked()}} />

So with this code when I click on one sets all checkboxes to checked, I suppose that they share one state. But I want for each component to have its own state and I don't know how to do it.

CodePudding user response:

You're right. It's because all the checkboxes use the same boolean state. To do the thing you want, you need to save each checkbox state separately. If your checkboxes have IDs, you can use a simple map like so:

const [isChecked, setIsChecked] = useState({});

const state = {
  isChecked,
  toggleCheck(id) {
    setIsChecked(isChecked => ({
      ...isChecked,
      id: !isChecked[id],
    }));
  },
};
<Checkbox
  checked={Boolean(context.isChecked[id])}
  checkedIcon={<CheckIcon/>}
  onChange={() => context.toggleCheck(id)}
/>
  • Related