0

I am trying to create multiple checkboxes with reactjs. But it not working what I did I do wrong? I have a state array set false to check each checkbox. I think it works but it didn't work How I fix it?

Thank you!

const GridResource = (resources) => {

  const [checked, setChecked] = useState([...Array(6)].map(x=>false));

  const handleCheckboxChange = (index) => {
      checked[index] = !checked[index];
      setChecked(checked);
  };


  const rows = [];
  resources.map((resource, index)=> {
    rows.push(
        <HeaderTable >
         <ChecboxGrid>
          <label>
           <Checkbox
               checked={checked[index]}
               onChange={()=> handleCheckboxChange(index)}
           />
          </label>
         </ChecboxGrid>

         <TagElement> {resource.firstName}</TagElement>
         <TagElement title={true}> {resource.lastName} </TagElement>
         <TagElement title={true}> {resource.jobtitle} </TagElement>
        </HeaderTable>
    )
  });

  return (

      <Container>
       <HeaderTable>

        <ChecboxGrid>
         <label>
          <Checkbox
              checked={checked}
              onChange={handleCheckboxChange}
          />
         </label>
        </ChecboxGrid>
       </HeaderTable>
       {rows}
      </Container>
  )
};

1 Answer 1

1

Don't mutate the state, create a copy so React can re-render

const handleCheckboxChange = (index) => {
     const copy = [...checked];
     copy[index] = !copy[index];
     setChecked(copy);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.