154

I am having trouble changing the view in react with routing. I only want to show a list of users, and clicking on each user should navigate to a details page. Here is the router:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from 'react-router-dom';
import Users from "./components/Users";
import { Router, Route } from "react-router";
import Details from "./components/Details";

ReactDOM.render((
  <BrowserRouter>
    <div>
        <Route path="/" component={Users} />
        <Route path="/details" component={Details} />
    </div>
  </BrowserRouter>
), document.getElementById('app'))

When I use the url /details my browser navigates to that url, but does not change the view. Any other route throws 404 so it seems to recognize the route but not update.

2
  • I am getting two errors: One stating that using proptypes from the main react package is deprecated. Two stating using React.createClass is deprecated. I thought this to be unrelated, as the code works without using routing.
    – MARyan87
    Apr 11, 2017 at 17:38
  • Is your component mounting correctly? Apr 12, 2017 at 3:33

37 Answers 37

112

You need to specify the attribute exact for your indexRoute, otherwise for even /details route it will still match with / . Also try to import Route from react-router-dom

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Route } from 'react-router-dom';
import Users from "./components/Users";

import Details from "./components/Details";

ReactDOM.render((
  <BrowserRouter>
    <div>
        <Route exact path="/" component={Users} />
        <Route path="/details" component={Details} />
    </div>
  </BrowserRouter>
), document.getElementById('app'))

UPDATE:

Another thing that you need to do is to attach your component Users with withRouter. You need to make use of withRouter only when your component is not receiving the Router props,

This may happen in cases when your component is a nested child of a component rendered by the Router or you haven't passed the Router props to it or when the component is not linked to the Router at all and is rendered as a separate component from the Routes.

In Users.js add

import {withRouter} from 'react-router';

.........
export default withRouter(Users)

DOCS

8
  • proptypes warning can be removed by installing npm install -S 'prop-types' and replacing React.PropsTypes with PropTypes . Also update your package.json to make use of the latest packaged since other packages may still be using React.PropTypes and React.createClass Apr 11, 2017 at 18:17
  • Also Do you try to reload the page when url changes to see if it loads Apr 11, 2017 at 18:18
  • I did try reloading page, it does not change the view. It loads into the Users view even if the url is /#/details
    – MARyan87
    Apr 11, 2017 at 18:25
  • 3
    Can you try the updated answer with Route imported from 'react-router-dom` instead of react-router Apr 11, 2017 at 18:34
  • 1
    It seems that import {withRouter} from 'react-router' this no longer works with new package. This answer becomes even more confusing.
    – twboc
    Aug 3, 2023 at 11:06
33

I had the same issue and discovered that it was because I had a nested router. Once I removed the nested router, and simply put my component-specific routes within a switch component--the issue was resolved without having to use withRouter or make any additional changes.

<Router> // <--Remove nested Router
    <Switch>
      <Route exact path="/workflows" component={ViewWorkflows} />
      <Route path="/workflows/new" component={NewWorkflow} />
    </Switch>
</Router>

Yusufbek is describing a similar issue. I think it's a lot cleaner to store the component related routes at a view level versus storing all of them in one main router. In a production app, that's going to be way too many routes to easily read through and debug issues.

3
  • 1
    I'm using create-react-app and this worked for me. Granted I built my router setup following some youtube tutorial, so create-react-app might not be related. Jan 11, 2021 at 5:45
  • @DustinEnglish was it dennis ivy youtube tutorial?
    – euh
    Jul 13, 2022 at 16:41
  • this did the trick for me too Mar 31, 2023 at 22:21
32

You just have to wrap the components inside withRouter.

<Route exact path="/mypath" component={withRouter(MyComponent)} />

Here is a sample App.js file:

...
import { BrowserRouter as Router, Route, Switch, withRouter } from "react-router-dom";
import Home from "./pages/Home";
import Profile from "./pages/Profile";

class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route exact path="/" component={withRouter(Home)} />
          <Route exact path="/profile" component={withRouter(Profile)} />
        </Switch>
      </Router>
    );
  }
}

export default App;

Additional

If you are using react router, componentWillReceiveProps will get called whenever the url changes.

componentWillReceiveProps(nextProps) {
    var currentProductId = nextProps.match.params.productId;
    var nextProductId = nextProps.match.params.productId; // from the new url
    ...
}

Note

Alternatively, you may also wrap the component in withRouter before exporting, but then you have to ensure a few other things. I usually skip this step.

export default withRouter(Profile)
1
  • 5
    < Route exact path="/mypath" component={withRouter(MyComponent)} /> worked for me Dec 2, 2018 at 4:48
31

React Router v5 doesn't work with React 18 StrictMode https://github.com/remix-run/react-router/issues/7870

2
  • 1
    Oh, this is IT! Big thanks! Somebody mentions in the link you provided, that a temp solution can be moving React Strict mode inside BrowserRouter, because apparently "It is not working if BrowserRouter is a child of StrictMode"
    – euh
    Jul 13, 2022 at 16:57
  • 1
    Awesome! This worked for me after burning hours trying everything.
    – Hammaad
    Nov 1, 2022 at 18:11
23

I have faced the same problem but I fixed it. I have placed the home page as the last. It works for me. Just like below.

    import React from "react";
    import ReactDOM from "react-dom";
    import { BrowserRouter } from 'react-router-dom';
    import Users from "./components/Users";
    import { Router, Route } from "react-router";
    import Details from "./components/Details";

    ReactDOM.render((
      <BrowserRouter>
        <div>
            <Route path="/details" component={Details} />
            <Route path="/" component={Users} />
        </div>
      </BrowserRouter>
    ), document.getElementById('app'))

1
  • 9
    Using the exact property would've also resolved this for you.
    – isherwood
    Jun 12, 2020 at 18:23
15

I had a similar issue but with different structure. I've added one Router that will handle all routes, I've used Switch component to switch views. But actually, it didn't. Only URL changed but not view. The reason for this was the Link component used inside of SideBar component which was outside of the Router component. (Yes, I've exported SideBar with "withRouter", not worked). So, the solution was to move my SideBar component which holds, all Link components into my Router.

The problem is in my linkers, they are outside of my router

<div className="_wrapper">
  <SideBar /> // Holds my all linkers
  <Router>
     <Switch>
       <Route path="/" component={Home} />
       <Route path="/users" component={Users} />
     </Switch>
  </Router>
 </div>

Solution was moving my linkers into my router

<div className="_wrapper">
  <Router>
     <SideBar /> // Holds my all linkers
     <Switch>
       <Route path="/" component={Home} />
       <Route path="/users" component={Users} />
     </Switch>
  </Router>
</div>
5
  • 4
    helping yourself made my day. I was trying it with two separated Routers. One was within the navbar and one within the body to accomodate the component. Now I put everything within the same Router in the parent component and things work as they should. Sep 11, 2019 at 17:39
  • 5
    Excellent - my exact issue. Thank you Nov 1, 2020 at 18:04
  • 3
    Thanks! You saved me!!
    – AzizStark
    Nov 4, 2020 at 18:49
  • 2
    I have tried everything, including withRouter, but only this solution did worked ... a bit of explanation would be helpfull to understand why this is happening
    – Jim
    Dec 19, 2020 at 11:59
  • 2
    @Jim I think react-router uses context API, and <Router /> aka <BrowserRouter /> provides a context to the route matchers like <Route />, <Switch /> and navigation components like <Link />, <Redirect />. In order to provide the same context, you have to wrap all children components within the context provider which is <Router />.
    – Yusufbek
    Dec 19, 2020 at 17:21
14

I had the same issue with react-router-dom 5

The problem was caused by the history package. The version I was using was 5.0.0 but they don't work together.

Fixed by downgrading history to 4.10.1

Related issue: https://github.com/ReactTraining/history/issues/804

0
12

According to this issue here, react-router-dom isn't compatible with React 18 because BrowserRouter is a child of StrictMode.

So to resolve the issue.

Instead of this:

<React.StrictMode><BrowserRouter>...</BrowserRouter></React.StrictMode>

Do this:

<BrowserRouter><React.StrictMode>...</React.StrictMode></BrowserRouter>

It worked for me this way, I hope it helps.

2
  • 3
    This worked for me in v5.3.1. Also v5.3.2 fixed this issiue. May 17, 2022 at 14:29
  • 2
    After hours of debugging, this fixed my issue (which was due to v5.3.0). Mar 16, 2023 at 12:25
9

BrowserRouter fails to maintain history in your case. Use "Router" instead, Usage of this with custom history as props may help resolve your problem.

import {Router, Route, Switch, withRouter } from "react-router-dom";
import Home from "./pages/Home";
import Profile from "./pages/Profile";
import {createBrowserHistory} from 'history';

export const customHistory = createBrowserHistory();  //This maintains custom history

class App extends Component {
  render() {
    return (
      <Router history={customHistory}>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/profile" component={Profile} />
        </Switch>
      </Router>
    );
  }
}

export default App;

Then in your components, import customHistory from 'App' and use that to navigate.

customHistory.push('/pathname');

Hope This help! :)

1
  • 2
    no need to the exact attribute when you use Switch
    – KBT
    Oct 20, 2020 at 20:00
8

When using Redux and I had similar issues where the url was updating in the address bar but the app was not loading the respective component. I was able to solve by adding withRouter to the export:

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

export default withRouter(connect(mapStateToProps)(MyComponentName))
1
  • But, it will work for functional component? Oct 6, 2021 at 8:22
7

In my case, I'd mistakenly nested two BrowserRouters.

5

You need to add exact to the index route and rather than enclosing those Route components by div, use Switch from react-router-dom to switch between the routes.

import React from "react";
import ReactDOM from "react-dom";
import { Route, Switch } from 'react-router-dom';
import Users from "./components/Users";

import Details from "./components/Details";

ReactDOM.render((
  <div>
    <Switch>
        <Route path="/" component={Users} exact/>
        <Route path="/details" component={Details} />
    </Switch>
  </div>
), document.getElementById('app'))
0
5

I Tried adding "exact" in front of the home path like this

<Route exact path="/" component={Home}></Route>

It is working fine...

1
  • Like, realy moving exact in front of to instead being it after helped. Want my hour of debugging back Jun 28, 2021 at 14:41
4

I had similar issue with React Router version 4:

By clicking <Link /> component, URL would change but views wouldn't.

One of views was using PureComponent rather than Component (imported from react) and that was the cause.

By replacing all route rendered components that were using PureComponent to Component, my issue was resolved.

(Resolution source: https://github.com/ReactTraining/react-router/issues/4975#issuecomment-355393785)

2
  • 1
    Thanks. That fixed it for me. But it was just the component that contained Switch that I had to extend from Component instead of PureComponent in order for live view changing to work. Oct 8, 2018 at 9:37
  • 1
    I've changed my pure component to component, it's not working for me though. Sep 13, 2019 at 19:46
4

None of the answers here solved my issue, turns out I had to add a dependency to my useEffect hook. I had something like this:

App.js

<Route
  path="/product/:id"
  component={MyComponent}
/>

MyComponent.jsx

const { id } = useParams();

useEffect(() => {
  fetchData();
}, []);

I had a button to change to another product, which would only update the :id on the url, I could see the url changed, but no effect on the page. This change fixed the issue:

MyComponent.jsx

const { id } = useParams();

useEffect(() => {
  fetchData();
}, [id]); // add 'id' to dependency array

Now when the id changes, it trigger a function to update the data and works as expected.

2
  • Dude, you are a life saver. I was trying to figure out what's going on for over 2 hours and your solution worked like a charm. I was doing the exact mistake. Thank you !
    – Enes
    Feb 18, 2022 at 16:13
  • In my case, I was returning a cleanup function in useEffect function which was unmounting the whole component. But, during the refresh, it loaded, because, the id remained the same and useEffect function was no more called.
    – iheathers
    May 15, 2022 at 6:50
2

Hmm there no any SWITCH to actually switch views.

this is how i use router to switch from landin page to main site

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


//App.jsx
render()
{
    return <div>
        <Switch>
            <Route exact path='/' component={Lander}/>
            <Route path='/vadatajs' component={Vadatajs}/>
        </Switch>
    </div>
}

https://jsfiddle.net/Martins_Abilevs/4jko7arp/11/

ups i found you use different router ..sorry then maybe this fiddle be for you useful

https://fiddle.jshell.net/terda12/mana88Lm/

maybe key of solution is hiden in line for main render function ..

Router.run(routes, function(Handler) {
    React.render(<Handler />, document.getElementById('container'));
});
0
2

I was facing similar issue I resolve to like this please have a look I hope it's working.

You need to use componentWillReceiveProps function in your component.

clicked a link first time by calling url www.example.com/content1/ componentDidMount() is run.

Now when you click another link say www.example.com/content2/ same component is called but this time prop changes and you can access this new prop under componentWillReceiveProps(nextProps) which you can use to call API Or make state blank and get new data.

componentWillReceiveProps(nextProps){
     //call your API and update state with new props
}
1
  • This function componentWillReceiveProps is now deprecated
    – Kevin
    Jan 7 at 16:44
2

For me, I had:

export MyClass extends React.Component

with:

export default withRouter(MyClass)

Meanwhile, in my App.js, I had:

import { MyClass } from './MyClass'

Those playing the home game can see my problem. I was not getting the import with the Router passed into the child classes. To clean this up, I moved the withRouter call into the Route component declaration:

<Router exact path={'/myclass'} component={withRouter(MyClass)} />

Back in MyClass, I changed it to a default export:

export default MyClass extends React.Component

And then finally, in App.js, I changed my import to:

import MyClass from './MyClass'

Hopefully this helps someone. This ensures I didn't have two ways to export the same class, thus bypassing the withRouter prepend.

2

I also had the same problem. Although it is not a very effective solution, I solved it with a cunning method. The ComponentDidMount method works every time our url changes. Within the method we can compare the previous url with the current url and we can the state change or page refresh.

componentDidUpdate(prevProps) {
    if (this.props.match.url !== prevProps.match.url) {
        //this.props.history.go(0) refresh Page
        //this.setState(...) or change state
    }
}
2
<Route exact path="/" component={Users} />
<Route exact path="/details" component={Details} />

I was also facing the same issue which was resolved using the exact attribute. try to use the exact attribute.

1

I met trouble too.

https://github.com/chengjianhua/templated-operating-system

And I have tried the solutions metioned by Shubham Khatri, but It doesn't work.


I solved this problem, maybe can help you.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md

According the above guide document, when you use PureComponent or use with state management tools like redux, mobx ... It may block the update of your route. Check your route component, ensure you did't block the rerender od your component.

1

You should check this out: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md

Therefore it's definitely not Users or Details, because they are directly rendered by <Route>, and the location will get passed to props.

I am wondering, why do you need the <div> between <BrowserRouter> and <Route>? Remove that and let me know if it works.

1

I had a similar issue with a conditional Layout:

class LayoutSwitcher extends Component {
  render () {
    const isLoggedIn = this.props.isLoggedIn
    return (
      <React.Fragment>
        { isLoggedIn
          ? <MainLayout {...this.props} />
          : <Login />
        }
      </React.Fragment>
    )
  }
}

and rewrote the conditions like so:

  render () {
    const isLoggedIn = this.props.isLoggedIn
    if (isLoggedIn) {
      return <MainLayout {...this.props} />
    }
    return <Login />
  }

This solved it. In my case, it seems that the context was lost.

1

I get the same Issue. I don't think that in this case he needs to add the prop withRouter, just check in your NavLink you write the good path name as details. for the route try to start from the specific route to the general one like

<Route path="/details" component={Details} />
<Route path="/" component={Users} />

in your NavLink it should be something like this

 <NavLink className="nav-link" to="/details">
   details<span className="sr-only">(current)</span>
 </NavLink>

a remarque for the import its better to start by importing all stuff related to React after that import the other module like this one:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from 'react-router-dom';
import Users from "./components/Users";
import { Router, Route } from "react-router";
import Details from "./components/Details";

come like this:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from 'react-router-dom';
import { Router, Route } from "react-router";

import Users from "./components/Users";    
import Details from "./components/Details";
1

In my case, switching to HashRouter instead of BrowserRouter solved my issue

1
  • Switching to hashrouter just for this usecase is not a good approch, it wont have access to state, history or anything... you'll miss a lot rich functionalities, and all of your urls will end with with # symbols Dec 30, 2022 at 12:22
1

I was accidentally using a BrowserRouter around my Link's.

<BrowserRouter>
    <div>
        <Link to="/" component={Users} />
        <Link to="/details" component={Details} />
    </div>
</BrowserRouter>
1

If you just started having this issue recently, take a look at https://github.com/remix-run/react-router/issues/7415

The issue is with react-router-dom 5+ and the history dependency.

If you installed it separately using yarn install history you need to uninstall it, do yarn install [email protected]

1

In my case it wasn't working because I imported Browser Router as Router, Like This:

<Router>

     <div> <Navbar/></div>

      <Routes>
         <Route exact path="/" element={<Pageone/>}></Route>
         <Route  path="/home" element={<Home/>}></Route>
         <Route  path="/about" element={<About/>}></Route>
         <Route  path="/contact" element={<Contact/>}></Route>  
      </Routes>

    
    <div><Footer /></div>


    </Router>
    </div>
  

Then It was fixed by adding BrowserRouter instead:

 <BrowserRouter>

     <div> <Navbar/></div>

      <Routes>
         <Route exact path="/" element={<Pageone/>}></Route>
         <Route  path="/home" element={<Home/>}></Route>
         <Route  path="/about" element={<About/>}></Route>
         <Route  path="/contact" element={<Contact/>}></Route>  
      </Routes>

    
    <div><Footer /></div>


    </BrowserRouter>
    </div>
  

Hope this helps someone!

0

Try this,

import React from "react";

import ReactDOM from "react-dom";
import Users from "./components/Users";
import { Router, Route } from "react-router";


import Details from "./components/Details";

ReactDOM.render((
  <Router>
        <Route path="/" component={Wrapper} >
            <IndexRoute component={Users} />
            <Route path="/details" component={Details} />
        </Route>
  </Router>
), document.getElementById('app'))
1
  • Define a Wrapper component which will render this.props.children. This will route properly. Apr 12, 2017 at 7:11
0

I had the same issue and I fixed it importing the history from the @types folder in node_modules. I imported it from npm (npm i @history)

Not the answer you're looking for? Browse other questions tagged or ask your own question.