import React, { useRef } from 'react'; function App() { // Step 1: Create a ref named inputRef using useRef() const inputRef = useRef(null); // Step 2: Define a function focusInput to focus the input element const focusInput = () => { // Step 3: Access the current property of inputRef to focus the input element inputRef.current.focus(); }; return ( <div> <h1>Focus Input Example</h1> {/* Step 4: Attach inputRef to an input element using the ref attribute */} <input type="text" ref={inputRef} /> {/* Step 5: Call focusInput function when the button is clicked */} <button onClick={focusInput}>Focus Input</button> </div> ); } export default App;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter