PresentationInteractive, narrated presentation of the section content.
ContentDetailed description of the section content.
In React, managing ref with React.forwardRef works similarly but integrates seamlessly with modern React features. The key advantage of forwardRef is that it lets you directly pass refs to child components, making them easier to manage without adding unnecessary complexity.
Here’s an explanation of using ref in React <19 with React.forwardRef and just ref with React 19+.
React.forwardRef with React 18.
Why Forward Refs?
In React, a ref assigned to a component points to the instance of the component (for class components) or null (for functional components). To access a DOM element inside a functional component, we need to forward the ref to the DOM element.
Basic Example: Managing an Input's Ref
Child Component Using forwardRef
import React, { forwardRef } from "react";
const Input = forwardRef((props, ref) => {
return <input {...props} ref={ref} />;
});
export default Input;
forwardRefensures the parent can pass arefto the internalinputelement.- The
refis passed as the second argument to the functional component.
Parent Component Using the Ref
import React, { useRef } from "react";
import Input from "./Input";
const Parent = () => {
const inputRef = useRef();
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<h1>Using forwardRef with React 18+</h1>
<Input ref={inputRef} placeholder="Type something..." />
<button onClick={focusInput}>Focus the Input</button>
</div>
);
};
export default Parent;
How It Works
InputComponent:- Wraps the DOM
<input>inReact.forwardRef. - Exposes the DOM
inputelement to the parent component.
- Wraps the DOM
- Parent Component:
- Creates a
refusinguseRef. - Passes the
refto theInputcomponent. - Calls DOM methods (e.g.,
.focus()) on theref.
- Creates a
Simplified Ref Handling in React 19
In modern React, you do not have to use forwardRef at all and just pass the ref as one of the props:
Example: Direct Ref on DOM Element
import React from "react";
const Input = ({ ref, ...props }) => {
return <input {...props} ref={ref} />;
});
export default Input;When forwardRef Is Needed
Use forwardRef only if:
- You wrap a DOM element in a custom component and need to expose the DOM element to the parent.
- The component should remain reusable with internal DOM access.
Key Takeaways
- Use
refdirectly for DOM elements where possible. - Use
forwardRefwhen building custom components that wrap DOM elements but still need to expose them. - React 19 simplifies the API but retains compatibility with
forwardReffor advanced scenarios.
Let me know if you'd like further details or a more advanced example! 🚀
No hints available.