Reputation: 23
What is the best way to accomplish what I am trying in the code below? App cannot access match.params for routes defined inside it, but I would like to pass parts of the state to child components based on the url params. I cannot use hooks like useRouteMatch() because App is a stateful class component. I think I can do this with the the Route render method, but it looks like React Router docs say that method is deprecated.
So is there a design pattern similar to this that lets me keep all route logic in App and just pass props to child components based on params, that doesnt use the render method of Route?
class App extends React.Component {
state = { things: this.props.things };
render() {
return (
<Switch>
<Route path='/thing/:thingId'>
<OneThing thing={this.state.things.find(thing => thing.id === match.params.thingId)} />
</Route>
<Route path='/things/:thingTag'>
<MultipleThings things={this.state.things.filter(thing => thing.tag === match.params.thingTag)} />
</Route>
</Switch>
);
}
}
Upvotes: 1
Views: 1940
Reputation: 3991
with <Route render>
<Route path='/thing/:thingId'
render={(route) => <OneThing thing={route.match.params.thingId} />} />
with <Route children>
ver 5.1
<Route
path='/thing/:thingId'
children={({ match }) => (
<OneThing thing={match.params.thingId} />
)}
/>
Upvotes: 1
Reputation: 116
try using withRouter
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
// A simple component that shows the pathname of the current location
class OneThing extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
render() {
const { match, location, history } = this.props;
return <div>You are now at {location.pathname}</div>;
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
export default withRouter(ShowTheLocation);
Upvotes: 0