Categories
React Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *