The Advanced Guide To ReactJs Checkboxes

January 20, 2018

How are checkboxes handled in ReactJS? Great question, I'm glad you asked! The truth is that forms inputs are handled a little differently in React. They can be controlled or uncontrolled.

An input is controlled if React's virtual DOM is constantly syncing the input value with state:

class App React.Component {
  constructor(props) {
      super(props);
      /* establish the initial state of the input field */
      this.state = {
        inputValue: ''
      }
    }
    /* update the input value in the virtual DOM */
  handleChange(event) {
    this.setState({
      inputValue: event.target.value
    });
  }
  render() {
    return (
      <input 
      value={this.state.inputValue}
      onChange={this.state.handleChange.bind(this)} />
    );
  }
}

in ReactJS, elements are controlled so that we can access (and manipulate) their value. If you're familiar with Jquery, the equivalent would be:

var inputValue = $('input').val();

Enough preamable. Here's how checkboxes work in ReactJs.

How Checkboxes Work In ReactJS

The overall strategy is to store the checkbox state (checked or unchecked) so that we can access it by other components or on form submission.

We do this with:

const checkbox = (
  <div>
    <input 
    type="checkbox"
    onClick={this.toggle.bind(this)}
    />
    <label>Checkbox</label>
  </div>
);

With an onClick event we call the class method toggle():

toggle(event) {
   this.setState({checkboxState: !this.state.checkboxState});
}

The toggle class method just negates the prior checkboxState. Checkboxes are easily controlled because they are necessarily binary - they can exist in the checked or unchecked state.

Putting It All Together

class App extends React.Component {
  constructor(props) {
      super(props);
      /* set the initial checkboxState to true */
      this.state = {
        checkboxState: true
      }
    }
    /* prevent form submission from reloading the page */
  onSubmit(event) {
      event.preventDefault();
    }
    /* callback to change the checkboxState to false when the checkbox is checked */
  toggle(event) {
    this.setState({
      checkboxState: !this.state.checkboxState
    });
  }
  render() {
    const checkedOrNot = [];
    checkedOrNot.push(
      <p>{this.state.checkboxState ? 'Unchecked' : 'Checked'}</p>
    );
    const checkbox = (
      <span>
        <input 
        type="checkbox"
        onClick={this.toggle.bind(this)}
        />
        <label>Checkbox</label>
      </span>
    );
    return (
      <div>
        <form onSubmit={this.onSubmit.bind(this)}>
          {checkbox}
          <button type="submit">Submit</button>
        </form>
        {checkedOrNot}
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));

A Working Example