React router doesnt route when clicking on link

Strahinja Ajvaz Source

so i have a header component with a couple of links:

{
    this.props.cats.map(x =>
        <li className="nav-item" key={x.path}><Link className="nav-link" to={x.path}>{x.name}</Link></li>)
}

The code snippet above is what i use to render the links

Then in my index.js(root) i use <BrowserRouter/> and it encompasses the whole element.

My question is to do with the routing i have implemented.

<Header />
<Switch>
  <Route exact path='/' component={(props) => <PostList cat='all' posts={this.props.posts} />} />
  <Route exact path='/:category' component={(props) => {
    console.log(props.match.url)
    return <PostList cat='filter' posts={this.props} />
  }} />
</Switch>

When i click on the link to take me to say path "/test" it should be picked up by the second Route element and every time it changes it should display the link, it doesn't. It will only change if i do a hard refresh.

Any idea on what i could be doing wrong?

Edit* included header component

<nav className="navbar navbar-expand-sm navbar-light bg-light mb-3">
        <div className="container">
          <Link className="navbar-brand" to='/'>Navbar</Link>
          <button className="navbar-toggler" data-toggle="collapse" data-target="#navbarNav"><span className="navbar-toggler-icon"></span></button>
          <div className="collapse navbar-collapse" id="navbarNav">
            <ul className="ml-auto navbar-nav">
              {
                this.props.cats.map(x =>
                  <li className="nav-item" key={x.path}><Link className="nav-link" to={x.path}>{x.name}</Link></li>)
              }
            </ul>
          </div>
        </div>
      </nav>
reactjsreact-routerreact-router-v4

Answers

answered 8 months ago nik7 #1

Link is now part of 'react-router-dom', make sure you have imported it from there ,if this doesn't solve your problem then try to wrap your component with withRouter

comments powered by Disqus