validate checkbox in React

In web development, a checkbox is a user interface element that allows users to select one or multiple options from a predefined set of choices. It is typically represented by a small square box that can be checked or unchecked.

In this tutorial, we validate checkbox in React and create corresponding functions to handle that.

How Does a Checkbox Work?

The checkbox element in HTML is created using the <input> tag with the type attribute set to “checkbox”. Here’s an example:

<input type="checkbox" name="option1" value="Option 1"> Option 1<br>
<input type="checkbox" name="option2" value="Option 2"> Option 2<br>
<input type="checkbox" name="option3" value="Option 3"> Option 3<br>

In the example above, we have three checkboxes labeled “Option 1,” “Option 2,” and “Option 3.” Each checkbox has a unique name and value attribute. When the form containing these checkboxes is submitted, the selected checkboxes’ values are sent to the server for processing.

How Does a Checkbox Work in Vanilla JavaScript?

In web development, you can use JavaScript to handle checkbox interactions and retrieve their state. Each checkbox has a checked property that you can access using JavaScript to determine if it is currently selected or not. You can attach event listeners to checkboxes to respond to user interactions, such as when a checkbox is clicked or its state changes.

Here’s an example of how you can use JavaScript to handle checkbox interactions:

<input type="checkbox" id="myCheckbox"> Check me!

<script>
  const checkbox = document.getElementById('myCheckbox');
  
  checkbox.addEventListener('change', function() {
    if (checkbox.checked) {
      console.log('Checkbox is checked!');
    } else {
      console.log('Checkbox is unchecked!');
    }
  });
</script>

Validate Checkbox in React

In React, you can use the input element with the type attribute set to “checkbox” to create a checkbox. Here’s an example of how to use checkboxes in a React component:

  <div className="container d-flex justify-content-center">
        <div className="col-md-4">
          <div className="input-group input-group-outline mb-3">
            <input type="checkbox" className="col-sm-4" onChange={this.handleUpdate}/>Can update
            <input type="checkbox" className="col-sm-4" onChange={this.handleApprove}/>Can approve
            <input type="checkbox" className="col-sm-4" onChange={this.handleDelete}/>Can delete
          </div>
        </div>
      </div>

Now, we can’t just handle this the way traditional JavaScript does by assigning it an id and then getting its value. We have to take a different approach.

We will create 3 functions that will handle the checkbox input as follows. But first, we have to create state variables.

constructor(props){
    super(props);
    this.state = {
      update: "",
      approve: "",
      delete: ""
    }
  }

These 3 state variables will be set when their respective checkboxes are clicked.

Next, we have to create 3 functions that will update the state variables.

handleUpdate(e) {
    this.setState({ update: e.target.checked });
  }
  
  handleApprove(e) {
    this.setState({ approve: e.target.checked });
  }
  
  handleDelete(e) {
    this.setState({ delete: e.target.checked });
  }

Next, we bind these functions to the state.

constructor(props){
    super(props);
    this.state = {
      update: "",
      approve: "",
      delete: ""
    }
    this.handleUpdate = this.handleUpdate.bind(this);
    this.handleApprove = this.handleApprove.bind(this);
    this.handleDelete = this.handleDelete.bind(this);
  }

We can quickly check if the function is returning any value as follows:

  handleUpdate(e) {
    this.setState({ update: e.target.checked }, ()=> {
      alert(this.state.update)
    });
  }
validate react checkbox

Next, we write a function that will check if the box is checked or not.

  validateUser = () => {
    const { update, approve, delete_privilege } = this.state;
    if(approve === ""){
    alert("specify approve privilege")
  }else if(update === ""){
      alert("specify update privilege")
    }else if(delete_privilege === ""){
      alert("specify delete privilege")
    }
  }

Here’s the result:

checkbox validation in react

This is how we validate checkbox in React

Here’s the full code

import React, { Component } from 'react';


class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      update: "",
      approve: "",
      delete_privilege: ""
    }
    this.handleUpdate = this.handleUpdate.bind(this);
    this.handleApprove = this.handleApprove.bind(this);
    this.handleDelete = this.handleDelete.bind(this);
  }

  validateUser = () => {
    const { update, approve, delete_privilege } = this.state;
    if(approve === ""){
    alert("specify approve privilege")
  }else if(update === ""){
      alert("specify update privilege")
    }else if(delete_privilege === ""){
      alert("specify delete privilege")
    }
  }

  handleUpdate(e) {
    this.setState({ update: e.target.checked }, ()=> {
      alert(this.state.update)
    });
  }

  handleApprove(e) {
    this.setState({ approve: e.target.checked });
  }

  handleDelete(e) {
    this.setState({ delete: e.target.checked });
  }

  render(){
    return(
      <div className="container d-flex justify-content-center" ><br />
      <div className="card-body">
      <ul className="list-group">
     <li className="list-group-item border-0 p-4 mb-2 bg-gray-100 border-radius-lg">
      <h6 className="mb-3 text-sm">Assign Privileges</h6>
      <div className="row">
        <div className="col-md-4">
          <div className="d-flex justify-content-center">
            <input type="checkbox" className="col-sm-2" onChange={this.handleApprove}/>
             Can approve
          </div>
        </div>

        <div className="col-md-4">
          <div className="d-flex justify-content-center">
            <input type="checkbox" className="col-sm-2" onChange={this.handleUpdate}/>
             Can update
          </div>
        </div>

        <div className="col-md-4">
          <div className="d-flex justify-content-center">
            <input type="checkbox" className="col-sm-2" onChange={this.handleDelete}/>
             Can delete
          </div>
        </div>

      </div>
    </li>
  </ul>
  <div className="text-end mt-4">
    <button  onClick={() => this.validateUser()} className="btn btn-success btn-lg mb-0">
    SUBMIT
    </button>
  </div>
</div>
</div>
    )
  }
}

export default App;

Conclusion

Overall, checkboxes are useful for allowing users to select one or multiple options from a list and are commonly used in forms, preference settings, and other interactive web components.

Conditional Rendering in React

Author

Leave a Reply

Your email address will not be published. Required fields are marked *