const rootEl = document.getElementById(\'root\');
ReactDOM.render(
Another solution is to use a state and lifecycle hooks in the routed component and a search statement in the to
property of the <Link />
component. The search parameters can later be accessed via new URLSearchParams()
;
<Link
key={id}
to={{
pathname: this.props.match.url + '/' + foo,
search: '?foo=' + foo
}} />
<Route path="/details/:foo" component={DetailsPage}/>
export default class DetailsPage extends Component {
state = {
foo: ''
}
componentDidMount () {
this.parseQueryParams();
}
componentDidUpdate() {
this.parseQueryParams();
}
parseQueryParams () {
const query = new URLSearchParams(this.props.location.search);
for (let param of query.entries()) {
if (this.state.foo!== param[1]) {
this.setState({foo: param[1]});
}
}
}
render() {
return(
<div>
<h2>{this.state.foo}</h2>
</div>
)
}
}
Use render method:
<Route exact path="/details/:id" render={(props)=>{
<DetailsPage id={props.match.params.id}/>
}} />
And you should be able to access the id using:
this.props.id
Inside the DetailsPage component
If you want to pass props to a component inside a route, the simplest way is by utilizing the render
, like this:
<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />
You can access the props inside the DetailPage
using:
this.props.match
this.props.globalStore
The {...props}
is needed to pass the original Route's props, otherwise you will only get this.props.globalStore
inside the DetailPage
.
Use the component:
<Route exact path="/details/:id" component={DetailsPage} />
And you should be able to access the id
using:
this.props.match.params.id
Inside the DetailsPage
component