We can control checking and unchecking of radio buttons and checkboxes using React state. Here we have to bind state variable to checked attribute of radio button or checkbox.

Program

Observe this code. Here we have bound the state variable checked to checked attribute of  radio button or checkbox.
import React from 'react';
import classNames from 'classnames';

class CheckAndUncheck extends React.Component {

  constructor(props) {
    super(props);
    this.checkIt = this.checkIt.bind(this);
    this.unCheckIt = this.unCheckIt.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      checked:false
    };
  }

  checkIt() {
    this.setState({
      checked:true
    });
  }

  unCheckIt() {
    this.setState({
      checked:false
    });
  }

  handleChange(evt) {
     if(this.state.checked !== evt.target.checked) {
        this.setState({
          checked:evt.target.checked
        });
     }
  }

  render() {
    return (
      <div>
        <div>
          <button onClick={this.checkIt}>Check</button> &nbsp;&nbsp;&nbsp; <button onClick={this.unCheckIt}>Uncheck</button>
        </div>
        <br/>
        <div>
          Checkbox :: <input type="checkbox" checked={this.state.checked} onChange={this.handleChange}/>
        </div>
        <br/>
        <div>
          Radio button :: <input type="radio" checked={this.state.checked} onChange={this.handleChange}/>
        </div>
      </div>
    );
  }
}

CheckAndUncheck.propTypes = {
}

CheckAndUncheck.defaultProps = {
}

export default CheckAndUncheck;

2 comments:

  1. Hey there!, I have improved the code's snippet, so the radio button's change event would be launched https://codesandbox.io/s/check-uncheck-radiobutton-lsyt7

    ReplyDelete
  2. Some of the features will allow you to view the games ivip9 สมัคร from different angles, change things about the environment, use autoplay so the game plays itself, or many other features.

    ReplyDelete

Blogroll

Popular Posts