when I use history.push url changes but doesn't render the component

Viewed 1814

I've seen problems like this but neither of them solved my problem.

I have a p tag that onClick is supposed to render a page. But when I click on it and use this.props.history.push(/posts/${id}) It changes the url but doesn't render the component I want.

I have tried using a

onClick={(e, id) => this.postPage(e, post.id)}

to trigger a function that will trigger the component I want to show up. I also tried using

<Link to-=''>

insted of

<p onClick>

but it doesn't work either.

This is what I have done so far, this is the function that triggers when I click the p tag:

 postPage = (e, id) => {
    const { history } = this.props;
    history.push(`/post/${id.toString()}`);
  }

and also, I used withRouter to have access to the history prop.

 export default withRouter(connect(null, mapDispatchToProps)(Post));

And these are the routes I mapped:

  render() {
     return (
       <div className="Routes">
        <Switch>
            <Route exact path='/' component={Home}></Route>
            <Route path='/post/:id' render={(history) => (
               <PostPage {...history}></PostPage>
            )}></Route>
          </Switch>
       </div>
    );
  }
}

And of course, when I call this component I also pass using BrowserRouter

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <Routes />
    </BrowserRouter>
  </Provider>
, document.getElementById('root'));

I just wanted to render the component but only the URL changes and nothing happens.

2 Answers

A good approach would be to implement react-redux and react-router-dom one at a time, to ensure that there are no clashes. The double HOC here:

export default withRouter(connect(null, mapDispatchToProps)(Post));

Is worth breaking down to:

export default withRouter(Post);

To ensure that react-router-dom works as expected, then implementing react-redux once routing is in place.

For those who have had the same problem the solution was to change the BrowserRouter tag location from the index.js to inside of the component that uses the Route. I was doing something like:

ReactDOM.render(<Provider>
<BrowserRouter>
<App>
</BrowserRouter>
</Provider>, document.getElementById('root'));

and now inside the Routes.js component

render() {
<BrowserRouter>
<Route ...>
<Route ...>
</BrowserRouter>

}
Related