Languages
[Edit]
EN

React - checkbox example (class component)

0 points
Created by:
Dirask Community
6240

In this article, we would like to show you how to use a checkbox in React.

Below example shows form as a class component with a single checkbox and submit button.

We use the component's state to store boolean agreement which we modify using setState method.

Practical example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      agreement: false
    };
  }

  handleChange = e => this.setState({ agreement: e.target.checked });

  handleSubmit = e => {
    e.preventDefault();
    console.log(`checked: ${this.state.agreement}`);
  };

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <div>
          <label>
            <input type="checkbox" 
              checked={this.state.agreement} 
              onChange={this.handleChange} />
            <span>Consent to the data processing</span>
          </label>
        </div>
        <button type="submit">Submit</button>
      </form>
    );
  }
};

const root = document.querySelector('#root');
ReactDOM.render(<Form />, root);

Note:

Go to this article to see functional component example.

ReactJS

React - checkbox (class component)
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join