React forward refs
Created By: chatGPT
In React, forward refs allow you to pass a ref from a parent component to a child component. This is useful in scenarios where you want to manipulate a DOM element within a child component directly from a parent component. Here’s how to use forward refs in your application.
import React, { forwardRef } from 'react';
const CustomInput = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
In this example, we create a functional component called
CustomInput
that uses forwardRef. The ref
will point to the <input>
element, allowing parent components to access the DOM node directly.const ParentComponent = () => {
const inputRef = React.useRef();
const handleFocus = () => {
inputRef.current.focus();
};
return (
<div>
<CustomInput ref={inputRef} placeholder='Type something...' />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
};
In the
ParentComponent
, we create a ref using useRef()
and pass it to the CustomInput
. The handleFocus
function, when called on button click, will focus the input field by directly manipulating the DOM node.export default ParentComponent;