1

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 />);
kunal verma
  • 456
  • 5
  • 13
  • This question has already been asked: [value of using React.forwardRef vs custom ref prop](https://stackoverflow.com/questions/58578570/value-of-using-react-forwardref-vs-custom-ref-prop) (Although I'm not 100% satisfied by the answers :/) – kca Mar 17 '23 at 19:10

2 Answers2

0

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

kunal verma
  • 456
  • 5
  • 13
0

if you want to konw why and how use ref ,you can view doc react ref

Cognia
  • 437
  • 3
  • 10