In this lesson, we make the Search input field focus on page load. To do this, we keep a reference of the input field with the useRef
hook, and trigger focus on that field when the component mounts with another React hook, useEffect
.
Simon Vrachliotis: [0:00] The search functionality sounds like a key feature of this app, but currently the user has to click on the input field before typing in a search. It would be nice if the input field was focused on loads, so the user can start typing.
[0:13] To do this, we need to get hold of a DOM element, the input field, and keep a reference to it. We'll use another React Hook to do this, useRef. Let's create a variable called inputRef = useRef. We'll add a ref prop to our inputs, which will be set to inputRef.
[0:34] If we console.log(inputRef) here, you can see that it has a current property which is the input itself. We can make this field focus imperatively by calling .focus on it. To release as soon as the search component is loaded, we will use yet another React Hook, useEffect. Import useEffect from "react".
[0:58] We'll call useEffect here, which takes a function, and we'll do inputRef.current.focus() in there. We only want that code to run once, so we'll pass an empty array of dependencies to the useEffect.
[1:11] Now, when we reload the app, the input field is focused, and we can start typing right away. Sweet.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!