const rootEl = document.getElementById('root'); ReactDOM.render( <BrowserRouter> <Switch> <Route exact path="/"> <MasterPage /> </Route> <Route exact path="/details/:id" > <DetailsPage /> </Route> </Switch> </BrowserRouter>, rootEl );
I am trying access the id in the DetailsPage component but it is not being accessible. I tried
<DetailsPage foo={this.props}/>
to pass parameters to the DetailsPage, but in vain.
export default class DetailsPage extends Component { constructor(props) { super(props); } render() { return ( <div className="page"> <Header /> <div id="mainContentContainer" > </div> </div> ); } }
So any idea how to pass the ID on to the DetailsPage ?
To pass parameters to component with React Router, we can use the useParams hook. <Route path="/details/:id" component={DetailsPage} />; to add the id parameter to our route. import { useParams } from 'react-router'; export default function DetailsPage() { const { id } = useParams(); // ... }
Getting the URL params In React router v4, you can access it using the props.match.params.id . In class-based components, you can access it like this. import React, { Component } from "react"; class Users extends Component { render() { const { id } = this.
Using react-router-dom v6import { useParams } from "react-router-dom"; const Something = (props) => { let { id } = useParams(); useEffect(() => { console. log(`/something/${id}`); },[]); // ..... } A quick and exact solution. Thanks for the details.
I used this to access the ID in my component:
<Route path="/details/:id" component={DetailsPage}/>
And in the detail component:
export default class DetailsPage extends Component { render() { return( <div> <h2>{this.props.match.params.id}</h2> </div> ) } }
This will render any ID inside an h2, hope that helps someone.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With