🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to React Notes
Topic #34

React Checkbox


Checkbox

For checkboxes, use the checked attribute instead of value to control its state.

We'll use the useState Hook to manage the value of the textarea:

In the handleChange function, use the e.target.type property check if the current input is a checkbox or not.

Example:

import { useState } from 'react';
import { createRoot } from 'react-dom/client';

function MyForm() {
  const [inputs, setInputs] = useState({});

  const handleChange = (e) => {
    const target = e.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;
    setInputs(values => ({...values, [name]: value}))
  }

  const handleSubmit = (event) => {
    let fillings = '';
    if (inputs.tomato) fillings += 'tomato';
    if (inputs.onion) {
      if (inputs.tomato) fillings += ' and ';
      fillings += 'onion';
    }
    if (fillings == '') fillings = 'no fillings';
    alert(`${inputs.firstname} wants a burger with ${fillings}`);
    event.preventDefault();
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>My name is:
      <input
        type="text"
        name="firstname"
        value={inputs.firstname}
        onChange={handleChange}
      />
      </label>

      <p>I want a burger with:</p>
      <label>Tomato:
      <input
        type="checkbox"
        name="tomato"
        checked={inputs.tomato}
        onChange={handleChange}
      />
      </label>
      <label>Onion:
        <input
          type="checkbox"
          name="onion"
          checked={inputs.onion}
          onChange={handleChange}
        />
      </label>
      <button type="submit">Submit</button>
    </form>
  )
}

createRoot(document.getElementById('root')).render(
  <MyForm />
);

Initial Values

To add initial values to the input fields in the example above, add the proper keys and values to the useState object:

Example:

function MyForm() {
  const [inputs, setInputs] = useState({
    firstname: 'John',
    tomato: true,
    onion: false
  });

  ...

Want to go beyond the notes?

Join CodingNow 2.0's React course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

React Checkbox – FAQs

Quick answers about learning React Checkbox in React.

This free note from CodingNow 2.0 explains React Checkbox in React — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every React topic on CodingNow 2.0, including React Checkbox, is 100% free with no signup required.
With focused practice, most students grasp React Checkbox in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now