freeBeerTomorrow freeBeerTomorrow - 2 months ago 34
React JSX Question

React-router New page renders and previous component stays on page after doing browserhistory.push('/path')

I have a routing setup like this in my app:

<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="/books" component={Main} url='/polls/getbooks/'/>
<Route path="/books/bookdetail" component={BookDetail} />
</Route>
</Router>


My App component looks like this:

class App extends React.Component {
pageContent() {
let content = <Spinner/>;

if (!this.props.dataLoading) {
content = (
<ReactCSSTransitionGroup
component="div"
transitionName="bobon-transition"
transitionEnterTimeout={500}
transitionLeaveTimeout={500}
transitionAppear={true}
>
{ React.cloneElement(this.props.children, {
key: this.props.location.pathname
}) }
</ReactCSSTransitionGroup>
);
}
return content;
}
}


And here is my Main component:

class Main extends React.component {

render() {

if(!this.state.loaded) {
return <Spinner/>
}

if(this.state.authed) {
content = (
<div >
<BookList apiData = {this.state.childData}/>
</div>
);
} else {
content = (
<div>
<LoginForm/>
</div>
);
}
return content;
}

}


When the user is logged in the page renders correctly and he sees the 'BookList' component. However in Booklist I navigate to a 'BookDetailView' using browserHistory.push('/books/bookdetail') when the user selects a book. The issue is that on the book detail view the 'BookList' component stays on page and the page looks like this:

<BookDetail>
<BookList>


If I was to type into my browser /books/bookdetail then the view would render correctly as

<BookDetail>


Why is the 'BookList' rendering on the bookdetail when I use browserHistory.push() page?

Many thanks.

Answer

When exporting your BookList component try to use the withRouter wrapper.

import { withRouter } from 'react-router';

class BookList extends React.Component {
  clickHandler() {
    this.props.router.push('/books/bookdetail');
  }
  render() {
  // if used in the render method you can use:
  // <h1 onClick={()=>this.props.router.push('/books/bookdetail')}>Book title</h1>
  }
}

export default withRouter(BookList);

More info:

https://github.com/ReactTraining/react-router/blob/master/docs/API.md#withroutercomponent-options

react - router withRouter does not inject router

Comments