sdgfsdh sdgfsdh - 3 months ago 17
React JSX Question

How do I modify the route parameters sent as props with React Router?

I have a React

Router
with routes like this:

<Router history={history}>
<Route path='/' component={App} />
<Route path='/:fileType/:fileId' component={App} />
</Router>


This puts props into my
App
like so:

{
fileType: 'whatever',
fileId: 'ABC5734'
}


However, I have designed my component so that it expects this format:

{
file: {
type: 'whatever',
id: 'ABC5734'
}
}


I would therefore like to transform the path props before they are sent to the component. Something like this:

<Router history={history}>
<Route path='/' component={App} />
<Route
path='/:fileType/:fileId'
component={(props) => <App file={{type: props.fileType, id: props.fileId}} />} />
</Router>


Is this possible?

Answer

React-router sends route params under this.props.params. So, correct your your code.

<Router history={history}>
  <Route path='/' component={App} />
  <Route 
    path='/:fileType/:fileId' 
    component={(props) => <App file={{type: props.params.fileType, id: props.params.fileId}} />} />
</Router>