Simpleton Simpleton - 6 months ago 165
Javascript Question

Re-using the same component twice with react-router

I have a react class called

MainContainer
which displays some content. It has a child,
SidebarContainer
that lists a bunch of links. I render my main container and by default load the first piece of content using a default ID of 1 as a fallback if there is no param value in the URL:

var MainContainer = React.createClass({
getInitialState: function() {
return {
selectedContent: this.props.params.slug || 1
},

componentWillReceiveProps: function(nextProps, nextState) {
this.setState({
selectedContent: this.props.params.slug || 1
});
},
}


The SidebarContainer component has a Link selector:

<Link to={content.slug}>
{content.title}
</Link>


When I click on the link, the browser's URL visibly changes, but nothing else happens. When I click again, the correct content renders. However, when I copy-paste a url with a specified param, it renders the correct content first time around.

My ReactDOM render method has the following react-router config:

ReactDOM.render((
<Router>
<Route path="/" component={MainContainer}/>
<Route path="/content/:slug" component={MainContainer}/>
</Router>
), document.getElementById('react-app'));


Am I using the
componentWillReceiveProps
lifecycle method incorrectly?

Answer

Inside componentWillReceiveProps, shouldn't you use nextProps instead of this.props?

this.setState({
      selectedContent: nextProps.params.slug || 1
});