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.
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 ) => {
...
CodePudding user response:
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, specificallymatch
, are not passed and the error occurs when accessingprops.match.params
. -
<Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />
When rendering on the
component
prop, the route props are passed along, soprops.match.params
works, but now you can't pass the additionalsarReport
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.