日本語

How to Store Multiple Checkbox Selections as an Array in React

​​React​Playwright,TypeScript

To store the selections of multiple checkboxes in React as an array, put the ids of the selected items in a string[] state and set each checkbox's checked with selected.includes(id). When a box is checked, create a new array with [...prev, id]. When it is unchecked, remove the id with prev.filter((x) => x !== id). Use this pattern for questions such as "Topics of interest (select all that apply)" in a survey or sign-up form.

For testing, I built a form that lets you choose from React, CSS, Git, and AWS. I drove Chromium with Playwright and checked the contents of the array after each selection.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transformed them with esbuild, and ran them in headless Chromium.

I did not test Firefox or Safari, touch operation on smartphones, reading by screen readers, long lists with hundreds of options, or form libraries such as React Hook Form.

Four checkboxes for topics of interest. Git, React, and AWS are checked in that order, then React is unchecked. The "selected order" array and the "display order" text below change with each click (the labels in the image are in Japanese)
Changes to the array and display across four clicks: check Git, React, and AWS in that order, then uncheck React

Store the selected ids in an array state

Define the options as pairs of id and label, and put only the ids of the selected items in the state.

tsx
export type Option = { id: string; label: string };

export const options: Option[] = [
  { id: 'react', label: 'React' },
  { id: 'css', label: 'CSS' },
  { id: 'git', label: 'Git' },
  { id: 'aws', label: 'AWS' },
];

The component is as follows. It decides whether a box is checked with selected.includes(o.id), and it uses e.target.checked from onChange to decide whether to add or remove the id.

tsx
import { useState } from 'react';
import { options } from './options';

export function TopicPicker() {
  const [selected, setSelected] = useState<string[]>([]);

  function handleChange(id: string, checked: boolean) {
    setSelected((prev) =>
      checked ? [...prev, id] : prev.filter((x) => x !== id),
    );
  }

  // Use the option order, not the selection order, for display and submission
  const ordered = options.filter((o) => selected.includes(o.id));

  return (
    <fieldset>
      <legend>興味のある分野</legend>
      {options.map((o) => (
        <label key={o.id}>
          <input
            type="checkbox"
            checked={selected.includes(o.id)}
            onChange={(e) => handleChange(o.id, e.target.checked)}
          />
          {o.label}
        </label>
      ))}
      <p data-testid="raw">選んだ順:{JSON.stringify(selected)}</p>
      <p data-testid="ordered">
        並び順:{ordered.map((o) => o.label).join('、') || 'なし'}
      </p>
    </fieldset>
  );
}

Passing a boolean to checked makes the checkbox a controlled input in React, so you must update the state in onChange (official reference: caveats for input). For setSelected, I pass a function that receives the current array prev and returns the next array. The spread syntax used for adding and the filter used for removing both return a new array without changing the original. These two patterns are introduced in the official documentation page on updating arrays in state.

The following shows how the array and the display changed when I checked Git, React, and AWS in that order and then unchecked React last.

text
Git をクリック → 選んだ順:["git"] / 並び順:Git
React をクリック → 選んだ順:["git","react"] / 並び順:React、Git
AWS をクリック → 選んだ順:["git","react","aws"] / 並び順:React、Git、AWS
React をもう一度クリック → 選んだ順:["git","aws"] / 並び順:Git、AWS
チェックボックス: React:off CSS:off Git:on AWS:on

The array is in click order, so re-sort it for display and submission

As the output above shows, adding with [...prev, id] keeps the array in click order, not in on-screen order. When I selected React second, the array became ["git","react"], which is the reverse of the option order (React first).

If the order of selection does not matter for the question, sort the values into the option order when displaying or submitting them. Then people who made the same choices get the same sequence of values. The ordered value in the component narrows the option list with filter, so it always follows the option order. The state itself stays in selection order, and the re-sorted array is computed on each render.

Using push does not update the screen

If you call push on the array state and then pass that same array to setSelected, the screen does not change when you click a checkbox. I checked this with the following component.

tsx
// Same imports as TopicPicker (omitted)

// Don't do this: push onto the current array and pass the same array to set
export function PushBug() {
  const [selected, setSelected] = useState<string[]>([]);
  const [count, setCount] = useState(0);

  function handleChange(id: string, checked: boolean) {
    if (checked) {
      selected.push(id);
    } else {
      selected.splice(selected.indexOf(id), 1);
    }
    setSelected(selected);
  }
  // Rendering is almost the same as TopicPicker (omitted). There is no display-order text; the array is shown as "selected items".
  // I also added a button that increments count by 1

After I clicked CSS and Git, I pressed a button that increments count, which is unrelated to the array. The result was as follows.

text
CSS をクリック → 選んだもの:[] / React:off CSS:off Git:off AWS:off
Git をクリック → 選んだもの:[] / React:off CSS:off Git:off AWS:off
別の state を更新 → 選んだもの:["css","git"] / React:off CSS:on Git:on AWS:off

Clicking CSS and Git did not check the boxes, and the display stayed at []. However, when another state was updated and the component re-rendered, the hidden ["css","git"] appeared and the boxes became checked. The contents of the array had changed through push, but the screen did not show them.

This happens because, if the value passed to the set function is Object.is-equal to the current state, React skips the re-render (caveats for the set function of useState). A pushed array is still the same array object even though its contents changed, so React treats it as the same value. The official reference also lists changing an array or object directly as a cause of the screen not updating after you update the state. sort and reverse also modify the original array, so when you reorder a state array, make a copy first.

Add a selection limit and a "clear all" button

A limit such as "up to 3 selections" can be enforced by the array length. When the limit is reached, set disabled on only the boxes that are not checked. A "clear all" button just puts an empty array into the state. To set an initial value, pass an array of ids to useState.

tsx
// Same imports as TopicPicker (omitted)

const MAX = 3;

export function LimitedPicker() {
  const [selected, setSelected] = useState<string[]>(['css']);
  const isFull = selected.length >= MAX;

  // handleChange is the same as in TopicPicker (omitted)

The following is the part of the rendering that contains the "clear all" button, the checkboxes, and the count display. The <fieldset> and <legend> are omitted.

tsx
      <button type="button" onClick={() => setSelected([])}>
        すべて外す
      </button>
      {options.map((o) => {
        const checked = selected.includes(o.id);
        return (
          <label key={o.id}>
            <input
              type="checkbox"
              checked={checked}
              disabled={!checked && isFull}
              onChange={(e) => handleChange(o.id, e.target.checked)}
            />
            {o.label}
          </label>
        );
      })}
      <p data-testid="limit-count">
        {selected.length} / {MAX} 件
      </p>

When I added React and Git to the initial CSS selection, the count reached 3 and the remaining AWS box became unselectable. Unchecking CSS made AWS selectable again, and "clear all" returned the count to 0.

text
初期表示 → 1 / 3 件 / React:off CSS:on Git:off AWS:off
React・Git をクリック → 3 / 3 件 / React:on CSS:on Git:on AWS:off(disabled)
AWS をクリックしようとした後 → 3 / 3 件 / React:on CSS:on Git:on AWS:off(disabled)
CSS を外す → 2 / 3 件 / React:on CSS:off Git:on AWS:off
すべて外す → 0 / 3 件 / React:off CSS:off Git:off AWS:off

If you only need the array on submit, read it with FormData.getAll

If you do not need to show the selections while the user is choosing or apply a limit, you can skip the state and read the array from the form at submit time. Give the checkboxes the same name and a value for each one, then read them with getAll on FormData.

tsx
import { useState, type FormEvent } from 'react';
import { options } from './options';

// Keep no state; take the array out of FormData when submitting
export function FormPicker() {
  const [sent, setSent] = useState<string[] | null>(null);

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const topics = formData.getAll('topics') as string[];
    setSent(topics);
  }

  return (
    <form onSubmit={handleSubmit}>
      {options.map((o) => (
        <label key={o.id}>
          <input
            type="checkbox"
            name="topics"
            value={o.id}
            defaultChecked={o.id === 'git'}
          />
          {o.label}
        </label>
      ))}
      <button type="submit">送信</button>
      <p data-testid="sent">送信した値:{JSON.stringify(sent)}</p>
    </form>
  );
}

sent is a state used only to display the array that was read. React does not hold the checkbox state here. The initial value is passed with defaultChecked (official reference: providing an initial value for an input).

I started with Git already checked, then checked AWS and React in that order and submitted. The array was in the order of the checkboxes in the form, not in click order. Submitting with everything unchecked gave an empty array.

text
送信 → 送信した値:["react","git","aws"]
全部外して送信 → 送信した値:[]

As described in the MDN explanation of checkboxes, an unchecked checkbox sends neither its name nor its value. So when nothing is selected, getAll returns an empty array (MDN: FormData.getAll()). If you forget to write value, every selected box sends on.

If you want to show the number of selections, apply a limit, or change other displays based on the selections, use the state-based approach described in the earlier sections.

​Posted by 86