Reactjs - Adding check all/uncheck all checkboxes

Viewed 48

I'm new and learning ReactJS and I'm trying to add a checkbox that will check/uncheck all of my other checkboxes. When I click on the "All" checkbox, the screen for the GUI goes white. The other checkboxes work as normal and are generated and assigned to data that is read from a DB based on data name. The handleAllToggle code is based on one that I found else where on here: https://codesandbox.io/s/wn09v3x4y7?file=/src/index.js

Please help.

import toggleItemLayer

this.state = {checkAll: true,
   itemList: [],
   fruitOrNot: new Map(),
   checkedItems: new Map()}

getItemList() {
   let url = myDbUrl;
   fetch(url)
      .then(resp => resp.json())
      .then(items => {
         this.setState({ itemList: items })
         for (let i = 0; i < this.state.itemList.length; i++) {
            if (this.state.itemList[i].name === 'Fruit') {
               this.setState({ fruitOrNot: this.state.fruitOrNot.set(this.state.itemList[i].name, 'Fruit') })
            } else {
               this.setState({ fruitOrNot: this.state.fruitOrNot.set(this.state.itemList[i].name, 'Not') })
            }
      })
      .catch(error => {
         console.log(error)
      });
}

handleItemToggle = async (event) => {
   let isChecked = event.target.checked;
   let item = event.target.value;
   this.setState({ checkedItems: this.state.checkedItem.set(item, isChecked) })
   
   let index = this.state.itemList.findIndex(element => element.name === item)
   await toggleItemLayer(this.sate.itemList[index], isChecked)
}

handleAllToggle = event => {
   let checkedItems = this.state.checkedItems;

   checkedItems.forEach(checkedItem => (checkedItem.isChecked = event.target.checked));
   this.setState({ checkedItems: checkedItems });
}

render() {
   return (
      <tr>
         <td style={{ paddingRight: '1em' }}><input
         type="checkbox"
         value="checkAll"
         defaultChecked={this.state.checkAll}
         checked={this.state.checkedSource}
         onChange={this.handleAllToggle}
         /></td>
         All
      </tr>

      this.state.itemList.map((item, index) => (
         <tr key={item.name}>
            <td style={{ paddingRight: '1em' }}><input
               type="checkbox"
               id={index}
               value={item.name}
               onChange={this.handleItemToggle}
               checked={this.state.checkedItems.get(item.name) === undefined ? true : this.state.checkedItems.get(item.name)}
            /></td>

        {/*additional properties code*/}

         </tr>   
   )
}
0 Answers
Related