Uncheck the parent checkbox on unchecking child elements in React App

Viewed 471

I have a check for Select All to check all/Uncheck all the child elements but when I uncheck any of the child elements I want to uncheck the parent checkbox as well. I can check and uncheck all when I select the SELECT ALL, but cannot achieve vice versa when any of the child element is unchecked.

export const List = props => {

    const{startOver} = props;

    const onCheckAllcheckbox = (event) => {
        let _items = props.items.map(item => {
            item.isChecked = event.target.checked
            return item;
        });
        props.setItems(_items);
    }

    const handleCheckChieldElement = (event) => {
        let _items = props.items.map(item => {
            if (item.id == event.target.value) {
                item.isChecked = event.target.checked
            }
            return item;
        })
        props.setItems(_items);
    }
return (
        <Box>
      
            {props.action && (
                <Box horizontal align="center">
              
                 <input type="checkbox"
                                onChange={onCheckAllcheckbox}
                                defaultChecked={true}
                                style={{width: '20px', height: '15px'}}  />
                    <Text>SELECT ALL</Text>
                </Box>
            )}
            <div style={{overflow : 'auto', height : '200px', width : '900'}}>
            <Box type="flat">
                {props.items.map((item, index) => (
                   
                    <Box key={index} horizontal align="center" style={{ margin: '.3rem 0' }}>
                        {props.action && (
                            <input type="checkbox"
                                onChange={handleCheckChieldElement}
                                checked={item.isChecked}
                                value={item.id}
                                style={{width: '20px', height: '15px'}} />
                        )}
                        {props.itemTemplate && props.itemTemplate(item) || (
                            <Text>{item.text}</Text>
                        )}
                    </Box>
                   
                ))}
                
            </Box>
            </div>
        </Box>
    )
}
1 Answers

Add checked attribute to Select All input instead of passing defaultChecked attribute.

<Box horizontal align="center">
      <input type="checkbox"
        onChange={onCheckAllcheckbox}
        checked={props.items.every((item) => item.isChecked)}
        style={{width: '20px', height: '15px'}}  />
      <Text>SELECT ALL</Text>
</Box>
Related