What is forwardRef in React?

In React, forwardRef is a function that allows a parent component to pass a ref directly to a child component, enabling the parent to access the child's DOM node or an imperative handle.

This is particularly useful for components that are wrappers around DOM elements or need to expose internal methods to their parent.

import React, { useRef, forwardRef } from "react";

const MyInput = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});

function App() {
const inputRef = useRef();

const handleFocus = () => {
inputRef.current.focus(); // Access the DOM input element
};

return (
<div>
<MyInput ref={inputRef} placeholder="Type here..." />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}

export default App;