Dev Helpers
← Back

Clearable search input

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

Open this example in the interactive library

Live preview

Source code

// components/ClearableSearchInput.tsx

import { useState, useRef } from "react";

export default function ClearableSearchInput({
  label = "Project notes",
}: { label?: string } = {}) {
  const [text, set] = useState("");
  const ref = useRef<HTMLInputElement>(null);
  return (
    <div>
      <label>
        {label}
        <input
          ref={ref}
          type="search"
          value={text}
          onChange={(e) => set(e.target.value)}
        />
      </label>
      <button
        disabled={!text}
        onClick={() => {
          set("");
          ref.current?.focus();
        }}
      >
        Clear
      </button>
    </div>
  );
}