Skip to content
Advertisement

Call function on default when checkboxes are rendered

this.state.pageData.map((elem) =>
  elem.map((ele) => {
    this.props.AllSelectedFlag ? (
      <Td>
        {' '}
        <Input type="checkbox" value={ele.id} checked={true} onClick={(e) => this.selectHandle(e, ele)} />
      </Td>
    ) : (
      <Td>
        <Input type="checkbox" value={ele.id} onClick={(e) => this.selectHandle(e, ele)} />
      </Td>
    );
  }),
);

Basically I have to check all the checkboxes when select all button is pressed, I am changing the state of AllSelectedFlag when button is pressed, but the problem is onClick button is not working when the condition is true.

Any other way to solve this?

Answer

Approach 1: If you have “checked” property

You don’t need to render and apply check properties for checkboxes, you just need to set “checked” property for all elements on “all” selection and reset.

And you can add event onChange on each checkboxes that will be used for individual check/uncheck part.

Refer to example: https://codesandbox.io/s/vvxpny4xq3

Approach 2: if you dont have “checked” property in json

Maintain local array with “ids” inside and oncheck/uncheck add/remove from it and use it for handling check related cases

    const [isCheckAll, setIsCheckAll] = useState(false);
    const [isCheck, setIsCheck] = useState([]);
    const [list, setList] = useState([]);

    const handleSelectAll = e => {
        setIsCheckAll(!isCheckAll);
        setIsCheck(list.map(li => li.id));
        if (isCheckAll) {
          setIsCheck([]);
        }
    };

    const handleClick = e => {
        const { id, checked } = e.target;
        setIsCheck([...isCheck, id]);
        if (!checked) {
          setIsCheck(isCheck.filter(item => item !== id));
        }
    };

Refer to example: https://codesandbox.io/s/react-select-all-checkbox-jbub2

Advertisement