Search code examples
javascripthtmlreactjsmaterial-uiweb-component

Checkbox issue oncheck function


Please see the following code at first. I want the particular checkbox (with id cfc1) to not be shown ticked whenever clicking on it. I have used the onCheck function there. I'm not finding any way to the particular element be shown unchecked whenever clicked on it. I'm trying using the code -

if(e.currentTarget.id === 'cfc1') {
    document.getElementById(e.currentTarget.id).checked = false; 
}

but it's not working.

How to do it using the onCheck function?

import React, {Component} from 'react';
import Checkbox from 'material-ui/Checkbox';

class Checkboxes extends Component {
  constructor() {
     super();
     this.state = {
        checkids:['cfc0', 'cfc1', 'cfc2', 'cfc3']
     };
     this.handleCheck = this.handleCheck.bind(this);
     this.getElements = this.getElements.bind(this);
  }
  getElements() {
     let arr = [];
     this.state.checkids.forEach(function(element) {
        arr.push(
          <Checkbox
             id={element}
             onCheck={this.handleCheck}
          />
        );
     }, this)
     return arr;
  }
  handleCheck(e) {
     console.log(e.currentTarget.id);
     console.log(e.currentTarget.checked);
  }
  render() {
     return(
       <div>
          {this.getElements()}
       </div>
     );
  }
}
export default Checkboxes

Solution

  • To get it working for your use case, try having a state variable that maintains the checked information of each element id.

    And in the onCheck handler toggle the checkbox for all the boxes except the one desired by setting the state.

    WORKING DEMO

    class App extends Component {
      constructor() {
        super();
         this.state = {
            checkids:{
              'cfc0': false,
              'cfc1': false, 
              'cfc2': false,
              'cfc3': false
            }
         };
      }
    
      handleCheck(e) {
         const checkids = {...this.state.checkids};
         checkids[e.target.id] = e.target.id === "cfc1" ? false : !checkids[e.target.id];
    
         this.setState({checkids});
      }
    
      getElements() {
         let arr = [];
         Object.keys(this.state.checkids).forEach(function(element, index) {
            arr.push(
              <Checkbox
                 key={index}
                 id={element}
                 checked={this.state.checkids[element]}
                 onCheck={this.handleCheck.bind(this)}
              />
            );
         }, this)
         return arr;
      }
    
      render() {
        return (
          <MuiThemeProvider>
            <div>
              {this.getElements()}
           </div>
          </MuiThemeProvider>
        );
      }
    }