Skip to content Skip to sidebar Skip to footer

React This.props.params Undefined

I have problem passing id to my page with product, I tried everything and search answer but it still doesn't work. Here is my index.js: import React from 'react'; import {render} f

Solution 1:

I was also getting the same problem when I used this.props.params.id.

But when i tried to put console.log(this.props) in the component where I'm passing the id, it shows my id in match object so use:

this.props.match.params.id

to get the id (notice the added match).

Solution 2:

For me I was using the render method and finding that this.props.match was undefined in rendered components. This was the solution for me, you have to pass in props.

this.props.match will be undefined for:

<Routepath='/users/:id'render={() =><UserDetail/>}/>

Do this instead:

<Route path='/users/:id' render={(props) =><UserDetail {...props}/>}/>

https://reacttraining.com/react-router/web/api/Route/render-func

Solution 3:

replace this :

<Routepath={"product/:id"} component={()=>(<div><Menu/><DetailsProduct>asd</DetailsProduct></div>)}></Route>

with :

<Routepath={"product/:id"} component={DetailsProduct}></Route>

Solution 4:

react router new version changed the route props object as the following: this.props.match.params instead this.props.params

https://reacttraining.com/react-router/web/api/match

Solution 5:

I assume you are not using react-router v4 but either v2.x.x or v3.x.x. In that case you should restructure your routes and you can pass multiple component using the components props as

<Routerhistory={hashHistory}><Routepath="/"component={Layout}><IndexRoutecomponents={{menu:Menu, mainPage:MainPage}}/><Routepath={"product/:id"} component={{menu:Menu, detail:DetailsProduct}}/></Route></Router>

And in the Menu Component Also the way you want it work is relatively very easy to do using react-router v4. In that case you can make use of prop render to provide a component and you could do the following with it

import {HashRouterasRouter, Route} from'react-router-dom';
...
<Router>
    <Routepath="/"render={()=>(<div><Menu/><MainPage/></div>)}></Route><Routepath={"product/:id"} render={()=>(<div><Menu/><DetailsProduct>asd</DetailsProduct></div>)}></Route>
</Router>

Post a Comment for "React This.props.params Undefined"