Accessing DOM Elements with useRef
Demonstrate how to use useRef to reference and manipulate a DOM element in a functional React component, such as focusing on an input field when the component loads.
import React, { useRef, useEffect } from 'react';Import the necessary hooks from React.
function MyComponent() {Declare a functional React component.
// Create a ref object using useRef which initially is set to `null`Instantiate a useRef hook for later reference to the DOM element.
const inputRef = useRef(null);Define a ref to attach to an input element.
useEffect(() => {Use the useEffect hook to perform actions after the component mounts.
// Check if the input element is referenced and focus on itFocus on the input field using the ref right after the component is rendered.
if (inputRef.current) {Verify that the ref is linked to an element.
inputRef.current.focus();Call the focus method on the input element once it is mounted.
}Close the if statement block.
}, []); // Pass an empty dependency array to only run once after initial renderingEnsure that the useEffect runs once after the initial render, hence the empty dependency array.
Render a text input element and attach the useRef created earlier with `ref` attribute.
return (Start returning JSX from the functional component.
<input ref={inputRef} type="text" />The input element that will be automatically focused.
);Close the JSX return block.
}Close the functional component block.
export default MyComponent;Export the functional component for use in other parts of the app.