This is a collection of tiny apps built with React, designed to explore and learn React along with its associated libraries. Each project serves as a hands-on experiment to try out new features and deepen understanding of the React ecosystem.
In React, forward refs provide a way for parent components to access and interact with a child component’s DOM nodes or refs. This is especially useful when you need to manipulate a child component’s elements, like focusing an input field or adjusting its styles, from the parent component.
Why Use Forward Refs?
Normally, refs are only available in the component where they are created. However, by using React.forwardRef
, you can pass the ref from the parent to the child, giving the parent control over the child’s DOM elements.
Example of Forward Refs:
import React, { useRef } from 'react';
// Child component accepting forwarded ref
const CustomInput = React.forwardRef((props, ref) => (
<input ref={ref} {...props} />
));
function ParentComponent() {
const inputRef = useRef(null);
const focusInput = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<div>
<CustomInput ref={inputRef} placeholder="Click the button to focus me" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default ParentComponent;
How It Works:
- The
CustomInput
component usesReact.forwardRef
to accept aref
prop from its parent. - In the
ParentComponent
,useRef
creates a reference, which is passed down toCustomInput
via theref
attribute. - The
focusInput
function triggers thefocus()
method on theinput
element inside theCustomInput
component, utilizing the forwarded ref.
Benefits of Forward Refs:
- Encapsulation: It allows child components to encapsulate logic while giving controlled access to the parent for specific operations like focusing or measuring size.
- Functional Components: Normally, only class components can handle refs directly. Forward refs allow functional components to receive refs too.
Conclusion:
Forward refs are an excellent tool when you need to build reusable components that can be manipulated from parent components. They bridge the gap between component encapsulation and direct DOM access, making it easier to handle specific UI operations.
Use the share button below if you liked it.
It makes me smile, when I see it.