The correct way of passing refs to child components as per react documentation is like this:
import React from 'react';
const Input = React.forwardRef((props, ref) => {
React.useEffect(() => {
ref.current.focus();
}, []);
return <input type="text" ref={ref} />;
});
export default function App() {
const inputRef = React.createRef();
return (
<div>
<Input ref={inputRef} />
</div>
);
}
But if i try to pass the created ref as a normal prop in any other name then 'ref', this also works as expected.
import React from 'react';
const Input = (props) => {
React.useEffect(() => {
props.inputRef.current.focus();
}, []);
return <input type="text" ref={props.inputRef} />;
};
export default function App() {
const inputRef = React.createRef();
return (
<div>
<Input inputRef={inputRef} />
</div>
);
}
So the question is, is forwardRef doing something special which we cannot achieve with normal props?
useRef
, search for createRef vs useRef. The rest is explained in the dup answer – Hedgerref
is a reserved word which cannot become a prop unless component is wrapped with awkwardforwardRef
– Liking