⊗jsrtPmHkURD 13 of 47 menu

Using the useRef DOM Hook in React

In one of the previous lessons we mentioned that refs are most often used to access DOM elements.

Refs will come to the rescue when, for example, you need to focus on an element, scroll, or calculate its size and position, or perhaps use some of its methods or properties, because there are no built-in methods for such things in React.

Let's look at an example with an input to see how this is done. Let's create a component with an input and a button:

return ( <div> <input /> <button>focus</button> </div> );

First, import useRef into the component:

import { useRef } from 'react';

And we'll create a ref ref in the component. We'll initialize it with the value null:

const ref = useRef(null);

Let's attach a click handler to the button:

<button onClick={handleClick}>focus</button>

To access the input, we write our ref ref to the attribute ref of the input. This way, when React creates a DOM node for this input, it will put a reference to it in ref.current and we will be able to use the input methods:

<input ref={ref} />

And finally, let's add a click handling function so that when the button is clicked, the input is focused. Now we can do this through the ref that contains the link to our input, by calling its focus method:

function handleClick() { ref.current.focus(); }

Press the button and make sure that the input is focused.

Take the code of the App component that we wrote in this lesson and make it so that when you click on the button in the input, in addition to setting the focus, the input field is also cleared. Use the value input property for this.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline