The answer to this question has changed dramatically over the years as React Router has been refactored again and again. Here is a breakdown of how to solve the issue with each version.
Version 6
The idea is to set the router to be a “browser router”, which is created using the createBrowserRouter() function. This router is then added to the root element of the React app.
import React from "react";
import ReactDOM from "react-dom/client";
import {
createBrowserRouter,
RouterProvider,
Route,
} from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: ...,
},
]);
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
Source react-router Version 6 Docs: createBrowserRouter
Version 4
For version 4 of react-router, the syntax is very different and it is required is to use BrowserRouter as the router root tag.
import BrowserRouter from 'react-router/BrowserRouter'
ReactDOM.render ((
<BrowserRouter>
...
<BrowserRouter>
), document.body);
Note that this will work in version 6, but it’s not recommended and the BrowserRouter component doesn’t support the new React Router data APIs.
Source React Router Version 4 Docs
Versions 2 and 3
For the versions 1, 2 and 3 of React Router, the correct way to set the route to URL mapping scheme is by passing a history implementation into the history parameter of <Router>. From the histories documentation:
In a nutshell, a history knows how to listen to the browser’s address bar for changes and parses the URL into a location object that the router can use to match routes and render the correct set of components.
In react-router 2 and 3, your route configuration code will look something like this:
import { browserHistory } from 'react-router'
ReactDOM.render ((
<Router history={browserHistory} >
...
</Router>
), document.body);
Version 1
In version 1.x, you will instead use the following:
import createBrowserHistory from 'history/lib/createBrowserHistory'
ReactDOM.render ((
<Router history={createBrowserHistory()} >
...
</Router>
), document.body);
Source: Version 2.0 Upgrade Guide