Checkboxes and React.JS

Over the past few weeks I’ve been teaching myself ReactJS for a new project on which I’m working. Along the way I’ve found all sorts of…

Checkboxes and React.JS

Over the past few weeks I’ve been teaching myself ReactJS for a new project on which I’m working. Along the way I’ve found all sorts of little things that are easy to do in Vanilla JavaScript, but are quite complicated in React. One such complication is handling forms. The webapp I’m currently building, PrizeFight — a daily fantasy sports app where users compete in free contests to win BitcoinCash, involves the use of checkboxes in selecting users’ fantasy rosters. Figuring out how to get checkboxes to work within my React app has been a serious pain in the ass, so for my own personal reference I’ve decided to go ahead and post this little example app demonstrating how to use checkboxes in React.

Note that we want to prevent the checkboxes from behaving as they normally would in Vanilla JavaScript. Instead, we want to set the “checked” property programmatically using the state of our React app. This is necessary because React makes it difficult to use Vanilla JavaScript to make calls such as this:

document.getElementById(“my-check-box”).checked = true;

Instead we will set the value of the “checked” property using state:

checked={this.state.checkboxSelected}

CheckBoxApp.js

import React, { Component } from 'react';
class CheckBox extends Component {
constructor(props) {
super(props);
    this.state = {
checkboxSelected: false
}
    this.toggleCheckBox = this.toggleCheckBox.bind(this);
}
  toggleCheckBox() {
this.setState({
checkboxSelected: !this.state.checkboxSelected
});
}
  render() {
return (
<div>
        <input
type="checkbox"
checked={this.state.checkboxSelected}
onClick={
function(event) {
this.toggleCheckBox();
}.bind(this)
}
/>
      </div>
);
}
}
class CheckBoxApp extends Component {
render() {
return (
<div>
        <h1>CheckBoxApp.js</h1>
        <CheckBox/>
        <CheckBox/>
        <CheckBox/>
      </div>
);
}
}
export default CheckBoxApp;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import CheckBoxApp from './CheckBoxApp.js';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<CheckBoxApp/>, document.getElementById('root'));
registerServiceWorker();

Citation: http://react.tips/checkboxes-in-react/