In my App.js
I have a ref
:
const canvasView1 = React.createRef();
...
<div ref={canvasView1}/>
And a route to a Homepage component with the ref as a prop:
<Route
index
path="/welcome"
element={<Homepage canvasView1={canvasView1}/>}
/>
Then, in Homepage.js
I use forwardRef()
and I log
the forwarded ref :
export const Homepage = React.forwardRef((props, canvasView1) => {
useEffect(() => {
console.log('# canvasView1 Homepage.js :', canvasView1)
}, [canvasView1]);
...
}
But it returns null
whereas in App.js
it returns the object:
CodePudding user response:
Since you are using React function components you'll want to use the
useRef
hook so the created ref is a stable reference.React.createRef()
will create a brand new React ref reference each render cycle.const canvasView1 = React.useRef();
The
Homepage
component is forwarding the specialref
prop, not any of the other regular named props that may or may not hold a React ref value. Pass thecanvasView1
ref on theHomepage
component'sref
prop so it's forwarded.<Homepage ref={canvasView1} />
or update the
Homepage
component to access the passedcanvasView1
prop.export const Homepage = ({ canvasView1 }) => { React.useEffect(() => { console.log("# canvasView1 Homepage.js :", canvasView1); }, [canvasView1]); return <h1 ref={canvasView1}>Homepage</h1>; });
Code:
export default function App() {
const canvasView1 = React.useRef();
React.useEffect(() => {
console.log("# canvasView1 App.js :", canvasView1);
}, [canvasView1]);
return (
<div className="App">
<div ref={canvasView1} />
<Routes>
<Route path="/" element={<Homepage ref={canvasView1} />} />
</Routes>
</div>
);
}