- useRef is a React Hook that returns a mutable object with a single property: current.
- You can use useRef to store a reference to a DOM element, a value that will persist across renders, or to store any other value that you want to persist between renders.
Here’s an example of using useRef to store a reference to a DOM element:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import React, { useRef } from 'react'; import ReactDOM from 'react-dom/client'; //App function component function App() {const myRef = useRef(null); const handleClick = () => { myRef.current.focus(); }; return ( <div> <input type="text" ref={myRef} /> <button onClick={handleClick}>Focus the input</button> </div> ); } const root = ReactDOM.createRoot(document.getElementById("root")); //creating a root React component in your application root.render(<App />) // rendering React components into a DOM node. |
Output:
