weissja19 weissja19 - 1 month ago 15
React JSX Question

How to explicitly pass router params to React Component?

Has anyone of you an idea how to pass the react-router params object explicitly to a component?

I want to make something like this, because unittesting would be easier if I could pass the ApiClient from outside:

function FooComponent() {
const apiClient = new ApiClient('http://foo.bar');
return (
<Bar apiClient={apiClient} param={?No idea how to pass the token param?} />
);
}

<Router history={history}>
<Route path="/test" component={Test} />
<IndexRoute component={TestIndex} />
<Route path="/validate/:token" component={FooComponent} />
</Router>


Thanks in advice!

Answer

If your component is attached to the route ( i.e. set as the component prop of Route as in your provided code ), it receives a prop params from react-router where you can get the route and query parameters. In your case:

function FooComponent(props) {
  const apiClient = new ApiClient('http://foo.bar');
  return (
    <Bar apiClient={apiClient} param={props.params} />
  );
}

For official example, look at : https://github.com/ReactTraining/react-router/blob/master/examples/query-params/app.js