Home > Software design >  Why forwarded refs with react-router-dom return null?
Why forwarded refs with react-router-dom return null?

Time:09-02

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:
enter image description here

I've read Edit react router v6 example (forked)

CodePudding user response:

  1. 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();
    
  2. The Homepage component is forwarding the special ref prop, not any of the other regular named props that may or may not hold a React ref value. Pass the canvasView1 ref on the Homepage component's ref prop so it's forwarded.

    <Homepage ref={canvasView1} />
    

    or update the Homepage component to access the passed canvasView1 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>
  );
}
  • Related