Dev HelpersOpen library
← Back

Select all fields

Import and render <SelectAllFields /> in a React project.

Open this example in the interactive library

Live preview

Source code

// components/SelectAllFields.tsx

import { useState } from "react";

export default function SelectAllFields({
  options = ["Clay", "Slate", "Ink"],
}: { options?: string[] } = {}) {
  const [values, set] = useState<string[]>([]);
  return (
    <fieldset>
      <legend>Include materials</legend>
      <button
        type="button"
        onClick={() => set(values.length === options.length ? [] : [...options])}
      >
        {values.length === options.length ? "Clear all" : "Select all"}
      </button>
      {options.map((v) => (
        <label key={v}>
          <input
            type="checkbox"
            checked={values.includes(v)}
            onChange={(e) =>
              set(e.target.checked ? [...values, v] : values.filter((x) => x !== v))
            }
          />
          {v}
        </label>
      ))}
    </fieldset>
  );
}