I would like to learn drawback or benefit of passing refs as a prop VS using React.forwardRef
In below example i am able to pass refForTextArea from "Aaa" component to "Bbb" component and focus onto textarea in Aaa from a button in "Bbb"
So why do we use React.forwardRef
import ReactDom from 'react-dom/client'
import React, { useRef } from 'react';
function Aaa() {
const refForTextArea = useRef();
return <div>Aaa
<textarea ref={refForTextArea}></textarea>
<Bbb props={{ x: 123, refForTextArea: refForTextArea }}></Bbb>
</div>
}
function Bbb({props}) {
const focuss = () => {
console.log(props);
props.refForTextArea.current.focus();
}
return <div>Bbb
<button onClick={focuss}>focus</button>
</div>
}
function App() {
return <div>Test
<hr></hr>
<Aaa></Aaa>
</div>
}
ReactDom.createRoot(document.getElementById('root')).render(<App />);
2
Answers
going through the docs https://reactjs.org/warnings/special-props.html Its due to separation of concert , it will just give a warning . Though not advised But doable
if you want to konw why and how use ref ,you can view doc react ref