Start learning free

LESSON 93 OF 161 · FRONTEND: REACT EFFECTS AND DATA

Refs: Reach an Element in JavaScript

Practice

Most of the screen comes from state: React draws it from your values. Some jobs aren't drawing, though: putting the cursor in a field, selecting text, scrolling. For those you need the element itself. A ref reaches it. useRef(null) gives a box with one property, current. Put the ref on an element with ref={…}, and once the element is on the page, React puts it in current.

An example on another element:

const noteRef = useRef(null);
// …
<textarea ref={noteRef} />
<button onClick={() => noteRef.current.select()}>Select all</button>

A ref is not state: changing ref.current doesn't make React draw again. Changing state does.

App passes SearchBox the search text as query and its setSearch as onChange. Clicking a button moves the focus to that button, so a Clear button must put it back in the field. Check types "lam" and clicks Clear:

> type "lam" into "Search"
  field "Search": "lam" (focused)
> click "Clear"
  field "Search": "" (focused)

Your task: in src/SearchBox.jsx, add a "Clear" button that empties the query and puts the focus back in the Search field, through a ref on the input.


Assignment
Follow the Coding Tutorial to give the search input a ref and write clear, which empties the query and focuses the field, with a Clear button that calls it.


Hint
Give the button the function clear itself, not clear(). Inside clear, inputRef.current is the input element, so you can call its focus().


STEP 1 OF 6
    Ctrl + Enter to check

    Effect Refs in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free