React: Focus and clear a field

Use a ref to reach an input element and move the cursor into it.

What to build

A field with buttons that focus it and clear it.

Requirements

  • An uncontrolled input with the id name, a button Focus that puts the cursor in it, and a button Clear that empties it and then puts the cursor in it.

Constraints

Use a ref; do not use document.getElementById or querySelector.

Example

Typing "Ada", then pressing Clear, empties the field with the cursor in it.

Why it works

The ref holds the real input element, so its focus method and value can be used directly, which is exactly what refs are for.

Hints

Hint 1

const inputRef = useRef(null); <input ref={inputRef} />.

Hint 2

inputRef.current.value = "" clears an uncontrolled input; then call focus().

Solution

Show one correct solution (try it yourself first)
import { useRef } from "react";

export default function App() {
  const inputRef = useRef(null);
  return (
    <div>
      <input id="name" ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
      <button
        onClick={() => {
          inputRef.current.value = "";
          inputRef.current.focus();
        }}
      >
        Clear
      </button>
    </div>
  );
}

Lesson: Refs: remembering without rendering →