A Ref to an Element
In the JavaScript course, you found elements with querySelector() and changed them yourself. In React, you rarely need to: you describe the page with JSX, and React changes the elements. But a few things can only be done with the element itself. The most common one is putting the cursor into a text field with its method focus(), so that the user can type straight away.
For that, React has refs (short for reference). You make a ref with the hook useRef, and give it to the element in the attribute ref:
import { useRef } from "react";
export default function TicketName() {
const nameRef = useRef(null);
function handleEdit() {
nameRef.current.focus();
}
return (
<p>
<input ref={nameRef} />
<button onClick={handleEdit}>Change the name</button>
</p>
);
}useRef(null) returns an object with one property, current, which starts as null. When React puts the input on the page, it stores the element in nameRef.current. From then on, nameRef.current is the same element that querySelector() would find, and a click on the button puts the cursor into the field.
React fills in the ref only once the element is on the page. During the first render, nameRef.current is still null. So use refs in handlers and in effects, which run after rendering, never in the JSX itself. An effect with [] can put the cursor into the field as soon as the component appears:
useEffect(() => {
nameRef.current.focus();
}, []);Why not just querySelector()? It searches the whole page, and a component doesn't know what else is on it. With two ticket forms on one page, it would always find the first one. A ref always points at this component's own element.
Instructions
Clear should also put the cursor back into the search field, so that the user can type another name. Create searchRef with useRef(null), give it to the field with ref={searchRef}, and in handleClear, call searchRef.current.focus().
Put the cursor into the field as soon as the app opens: add an effect with the dependencies [] that calls focus(). Click Run, and you can type at once.