bhylu.com

Advertisements

React Checkboxes and Radio Buttons

Control checkboxes with checked and group radio buttons by the decision they represent.

How it works

A checkbox describes an independent true-or-false choice. Radio buttons describe one choice from a group, sharing a name and different values. Read event.target.checked for a checkbox rather than treating its value as the boolean. The example combines a bag reminder with a pickup mode. A fieldset and legend name the radio decision, while each control keeps its own visible label.

Run the code

Use a separate empty lab folder with Node 22.12+ in the 22 series. Save the files below using their displayed paths; browsers may download only the basename, so create src, public or tests folders as listed. The pinned project uses React and React DOM 19.3.1 with Vite 7.3.1. Run npm install, then npm run dev and open the local address Vite prints. React examples do not run in Bhylu’s current playground.

No Apache, MySQL or change to Bhylu’s server configuration is needed. These are local teaching projects, not a publishing package. Keep generated dependencies and lockfiles in your own lab. Review the project setup.

Example

src/main.jsx

import React, { StrictMode, useState } from 'react';
import { createRoot } from 'react-dom/client';
import './style.css';

function App() {
  const [bag, setBag] = useState(false);
  const [mode, setMode] = useState('walk');
  return (
    <main>
      <h1>Neighbourhood lending desk</h1>
      <label>
        <input
          type="checkbox"
          checked={bag}
          onChange={(event) => setBag(event.target.checked)}
        />
        Bring a bag
      </label>
      <fieldset>
        <legend>Pickup mode</legend>
        {['walk', 'cycle'].map((value) => (
          <label key={value}>
            <input
              type="radio"
              name="mode"
              value={value}
              checked={mode === value}
              onChange={(event) => setMode(event.target.value)}
            />
            {value}
          </label>
        ))}
      </fieldset>
      <output>
        {mode} · {bag ? 'bag reminder on' : 'no bag reminder'}
      </output>
    </main>
  );
}

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
);

Expected result

Selecting cycle and enabling the reminder produces “cycle · bag reminder on”.

The radio group has one state value, so two modes cannot be selected at once. The checkbox has a separate boolean because it is independent. Keep these choices separate from permission or consent for unrelated purposes. If a required acknowledgement affects a real workflow, explain its meaning and validate it at the server boundary as well.

For API contracts and version differences, use React’s official documentation.

Advertisements