React router link doesn't refresh automatically

Viewed 1272

When I click a Link, the url changes, but the content of the page doesn't change unless I manually refresh my browser. Why is this? I use React Router v5.

Here's my code in App.js

function App() {
  return (
    <Router>
      <div style={tempStyles}>
        <Switch>
          <Route exact component={Quiz} path="/quiz" />
          <Route exact component={Home} path="/" />
        </Switch>
      </div>
    </Router>
  );
}

And here's my Home.js

function Home() {
  return (
    <Router>
      <div>
        <Link to="/quiz">
          Take the quiz
        </Link>
      </div>
    </Router>
  );
}
2 Answers

Wherever you defined your routes make path exact={true}, this will fix your problem. The main problem is that we often don't use exact={true} when defining routes and as a consequence the actual component does not renders until refreshed.

For ex - Suppose I defined for '/path' render TempComponent and for 'path/actual' render ActualComponent. So what happen if I don't set exact={true} for '/path' and '/path/actual', react-router will render TempComponent for '/path/actual' because it is matching the url '/path' even though partially if we set exact={true} then for '/path/actual' it'll not render TempComponent instead it'll render ActualComponent

I Had the same problem and it turns out there should be only one component. In your case try removing the Component from Home.js.

function Home() {
   return (
      <div>
         <Link to="/quiz">
          Take the quiz
         </Link>
      </div> 
   );
}
Related