Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Pass Param to Component

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 ?

like image 571
M T Avatar asked Aug 26 '17 19:08

M T


People also ask

How do I pass parameters in react router?

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(); // ... }

How do I get params from react router in class component?

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.

How do you get params in component in react dom v6 router?

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.


2 Answers

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.

like image 75
Alexander Luna Avatar answered Oct 02 '22 09:10

Alexander Luna


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.

like image 36
Win Avatar answered Oct 02 '22 09:10

Win