How to fix React Router changing URL but not the view?

Sometimes, we want to fix React Router changing URL but not the view

In this article, we’ll look at how to fix React Router changing URL but not the view.

How to fix React Router changing URL but not the view?

To fix React Router changing URL but not the view, we should set exact for the route components that aren’t rendering.

For instance, we write

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")
);

to add the exact prop to the first Route so that Users is rendered when we go to /.

The Routes that have more specific path values don’t need exact since they don’t match other Routes.

Conclusion

To fix React Router changing URL but not the view, we should set exact for the route components that aren’t rendering.