skip to Main Content

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


  1. Chosen as BEST ANSWER

    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


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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search