I can find multiple examples/docs explaining how we can pass a ref to function component using forwardRef
but never found any explanation WHY we use forwardRef
at all.
Here's my codepen to demonstrate my point.
In both cases, clicking the "focus" button next to the input will focus the input to left. The first input utilizes forwardRef
while the second doesn't.
Here's the source code for SEO:
import * as React from "https://cdn.skypack.dev/react@17.0.1";
import * as ReactDOM from "https://cdn.skypack.dev/react-dom@17.0.1";
const WithForwardRef = React.forwardRef((props, ref) => {
return <input type="text" placeholder="WithForwardRef" ref={ref} />;
});
const WithoutForwardRef = ({ myRef }) => {
return <input type="text" placeholder="WithoutForwardRef" ref={myRef} />;
}
function App() {
const ref1 = React.useRef();
const ref2 = React.useRef();
return (
<>
<div>
<WithForwardRef ref={ref1} />
<button onClick={() => ref1.current.focus()}>focus</button>
</div>
<hr>
<div>
<WithoutForwardRef myRef={ref2} />
<button onClick={() => ref2.current.focus()}>focus</button>
</div>
</>
);
}
ReactDOM.render(<App />, document.getElementById("mainApp"));