React Foundations · TypeScript

Typing refs

Typing refs

A ref gives you a handle on a real DOM node so you can read it or call its methods. useRef returns an object whose .current holds that node, and it starts as null because the node does not exist until React has rendered it. Tell the ref what kind of node it will hold with a type argument:

const inputRef = useRef<HTMLInputElement>(null);

Now .current is an HTMLInputElement or null, so the compiler knows the element's real API. Attach the ref to the element with ref={inputRef}, and from then on .current points at that input. Read it behind a guard, because the first render has no node yet:

function readName() {
  setName(inputRef.current?.value ?? '');
}

.value is checked against HTMLInputElement, so a property or method the element does not have is a compile error. A <div> would take useRef<HTMLDivElement>(null); each element has its own interface. The type argument is what makes .current useful — without it the compiler cannot tell you what the node can do.

Your job is to type a ref in App.tsx.

Challenge

A button should read an input's current text through a ref. Export an App component from App.tsx that creates useRef<HTMLInputElement>(null) and attaches it to a text input with ref={inputRef}, whose defaultValue is Ada. Render a Read button that stores inputRef.current?.value in state, and a paragraph showing that value.

The Test clicks Read and expects the paragraph to read Ada. The starter renders the input and button but reads nothing, so the Test fails.

App.tsx
export function App() {
  return (
    <div>
      <input aria-label="Name" defaultValue="Ada" />
      <button>Read</button>
      <p></p>
    </div>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.