Hello Devs, 

In this tutorial, we will learn React Checkbox onchange | React Checkbox Example

In this section, we will take simple "i_agree" with checkbox input and add onchange event with handleChange() then we will assign value on state variable array. Then on submit event we will take that values with state variable.

Follow this step by step guide below. 



Example Code:

import React, { Component } from 'react';
import { render } from 'react-dom';
      
class App extends Component {
  constructor() {
    super();
    this.state = {
      i_agree: false
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
     
  handleChange(event) {
    this.setState({i_agree: !this.state.i_agree});
  }
     
  handleSubmit(event) {
    console.log(this.state);
    event.preventDefault();
  }
     
  render() {
    return (
      <div>
        <h1>React Checkbox onChange Example - rathorji.in</h1>
        <form onSubmit={this.handleSubmit}>
           
          <label>
            <input
              type="checkbox"
              defaultChecked={this.state.i_agree}
              onChange={this.handleChange}
            /> I Agree with this content...
          </label>
           
          <input type="submit" value="Submit" />
        </form>
      </div>
    );
  }
}
   
render(<App />, document.getElementById('root'));



Output: 

{i_agree: true}


May this example help you.