Vincent Decaux
Vincent Decaux

Reputation: 10714

ReactJS - link to doesn't work for URL with parameter

I use ReactJS and react-router-dom (version 4.2). I can't have my links working with :

<Link to={'/site/' + site.id}>
    <h5><Icon name="map-marker"/> {site.title}</h5>
</Link>

It works when I am on home page (http://localhost:3000), the component is rendered, but when I am on a page like : http://localhost:3000/site/1, I can't go to URL http://localhost:3000/site/2.

The URL changes in address bar, but nothing happens.

I use :

...
<Route path="/site/:id" render={(props) => (
    <SitesView id={props.match.params.id} />
)}/>
...

export default connect(mapStateToProps, mapDispatchToProps, undefined, { pure: false })(App);

In my Router. I can't get it, is it because the URL are almost the same ?

Upvotes: 0

Views: 972

Answers (1)

Amir Mohammad Moradi
Amir Mohammad Moradi

Reputation: 887

As I understood , you have one component <SitesView/> for all of the /site/ routes with different props.id's.

When you change the parameter of URL, the id of <SitesView/> component and the URL will be changed but be noticed the <SitesView/> is rendered on previous route and at the moment you are seeing this rendered component which has no knowledge aboute the changes.

Then you need to use one of the React LifeCycle Methods named componentWillReceiveProps(nextProp, nextState) to get to know when the id of <SitesView/> changed. and based on new id you can update your component.

Upvotes: 2

Related Questions