Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router or Link Not Rendered

I am using react-router-dom in a redux app.

This is my initial setup in index.js:

ReactDOM.render(

  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>

  , document.getElementById('root'));

Then in my App.js I have:

render() {
    return (
      <div className="App">
        <Route exact path="/" render={ () => {
          return (
              <div>
                {
                  this.props.categories.map((category)=>{
                    console.log('category', category)
                    return (
                          <Link key={category.name} to="/category"  >{category.name}</Link>
                    )
                  })
                }
              </div>
          )

          }}
        />

        <Route path="/category" render={ () => {
          console.log('category path this.props', this.props)
          return (<p>Category is whatever</p>)
        }}
        />

      </div>
    );
  }

I would think that whenever I click any of the Links displayed the browser would automatically know how to render the new Route path /category but for some reason it does not.

What am I doing wrong?

like image 874
preston Avatar asked Nov 03 '17 05:11

preston


People also ask

Why my component is not rendering in react?

There are two common reasons why React might not update a component even though its props have changed: The props weren't updated correctly via setState. The reference to the prop stayed the same.

What is the difference between route and Link in react?

So in a nutshell, the Link component is responsible for the transition from state to state (page to page), while the Route component is responsible to act as a switch to display certain components based on route state.

What is the difference between BrowserRouter and router in react?

At the core of every React Router application should be a router component. For web projects, react-router-dom provides <BrowserRouter> and <HashRouter> routers. The main difference between the two is the way they store the URL and communicate with your web server. A <BrowserRouter> uses regular URL paths.

Is react router necessary?

Need for React RouterIt enables the creation of single-page web or mobile apps that allow navigating without refreshing the page. It also allows us to use browser history features while preserving the right application view. A Router in React JS routes using a component-based architecture.


1 Answers

The above post by Dane has the solution. But in the spirit of presenting the solution with more clarity, I will copy and paste the relevant codes that made react router work well with redux and other middleware.

import { withRouter } from 'react-router-dom'



export default withRouter(connect(
  mapStateToProps,
)(App))
like image 80
preston Avatar answered Oct 10 '22 21:10

preston