Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does Route with children as components cause Typeerror, but route with component does not?

I’m using "react-router-dom": "5.2.0". According to this stack post and blog to pass props to a component from route all I need to do is simply pass it like so:

{caseManagement && <Route path={`${SPA_PREFIX}/cases/:caseToken`}> <CaseView sarReport={sarReport} /> </Route>}

However, when I do this my complier doesn’t complain, but in my browser I get the following error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

CaseView.jsx:48 Uncaught TypeError: Cannot read properties of undefined (reading 'params') at CaseView (CaseView.jsx:48:1)

If I change the code to the following it works as expected.

{caseManagement && <Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />}

Of course in this implementation I’m not passing any props to it. How can I pass props to my component?
Below is the relative code of the component I’m passing props to

const CaseView = ({
  match: { params: { caseToken } },
}, sarReport ) => {
...

>Solution :

Issues

  • <Route path={`${SPA_PREFIX}/cases/:caseToken`}>
      <CaseView sarReport={sarReport} />
    </Route>
    

    When rendering CaseView as a child you can pass any props you like, but the route props, specifically match, are not passed and the error occurs when accessing props.match.params.

  • <Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />
    

    When rendering on the component prop, the route props are passed along, so props.match.params works, but now you can’t pass the additional sarReport prop.

Solution

In react-router-dom v5 to pass along the route props (i.e. history, location, and match) and other custom props you should use the render function prop.

Example:

<Route
  path={`${SPA_PREFIX}/cases/:caseToken`}
  render={routeProps => <CaseView {...routeProps} sarReport={sarReport} />}
/>

See Route render methods for further detail and explanation between the different methods for rendering routed components.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading