react-router v4 NavLink is not changing URL

1.9k Views Asked by At

when I started the project I did not work with create-react-app I built the basic react-flux app like always which is with browserify and babelify and all and the react-router v4 was working and no problem happened

then I immigrated to create-react-app env to use the testing and building tools that is offered

and I installed all packages that I used previously properly but react-router v4 had a problem

when I click NavLink, it does not change the URL but when I change the URL manually it works fine

I use BrowserRouter like this:

    <BrowserRouter history={HashRouter}<App /></BrowserRouter>,document.getElementById("root"));

And NavLink like this:

    <NavLink className="nav-link" activeClassName="active" to={"/drugs"}>
                            <i className="fa fa-medkit" aria-hidden="false"/>
                            &nbsp;Drugs
                        </NavLink>

And Router like this:

   <Switch>
                <Route exact={true} path="/" component={Patients}/>
                <Route exact path="/drugs" component={Drugs}/>
                <Route exact path="/settings" component={Settings}/>
                <Route path="*" component={Error}/>
            </Switch>

and thanks in advance.

2

There are 2 best solutions below

0
On

Most likely your component does not update properly. This can happen if you inherit from React.PureComponent instead of React.Component or mess up with the method shouldComponentUpdate().

If you can't figure it out (you should), you can still pass the location object manually with the HOC withRouter from react-router-dom like so :

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

const Menu = ({ location }) => (
  <menu>
    <NavLink
      className="nav-link"
      activeClassName="active"
      location={location}
      to="/drugs"
    >
      <i className="fa fa-medkit" aria-hidden="false" />
      &nbsp;Drugs
    </NavLink>
  </menu>
);

export default withRouter(Menu);

Note: Most imports have been stripped out for clarity

6
On

The problem is <Navlink to={"/drugs"}. When you use {} You're indicating that you'll be using JS, and since "/drugs" is not valid js it fails.

Instead remove the {}.

<NavLink className="nav-link" activeClassName="active" to="/drugs">