How to Update HashRouter in React
Updating HashRouter in your React applications primarily
involves migrating from React Router v5 to React Router v6. This guide
provides a direct, step-by-step walkthrough of how to update your
configuration, adapt to the new routing syntax, and implement modern
programmatic navigation using the latest standards of
react-router-dom.
Step 1: Update the Dependency
First, ensure you are running the latest version of
react-router-dom. Run the following command in your project
terminal:
npm install react-router-dom@6Step 2: Update the Router Syntax
In React Router v6, the way routes are nested and rendered inside
HashRouter has changed. The <Switch>
component has been replaced by <Routes>, and the
component or render prop on
<Route> has been replaced by the element
prop.
Old Syntax (React Router v5)
import { HashRouter, Switch, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<HashRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</HashRouter>
);
}New Syntax (React Router v6)
To update your HashRouter implementation, wrap your
<Route> components in <Routes> and
pass your components as JSX elements to the element
prop:
import { HashRouter, Routes, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';
function App() {
return (
<HashRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</HashRouter>
);
}Note: The exact prop is no longer needed in v6, as
paths match exactly by default.
Step 3: Update Programmatic Navigation
If you previously used the useHistory hook to navigate
programmatically inside a HashRouter context, you must
update it to use the new useNavigate hook.
Old Navigation (v5)
import { useHistory } from 'react-router-dom';
function HomeButton() {
let history = useHistory();
return (
<button onClick={() => history.push('/home')}>
Go Home
</button>
);
}New Navigation (v6)
Replace useHistory with useNavigate. The
new hook returns a function that you can call directly to navigate to
different hash paths:
import { useNavigate } from 'react-router-dom';
function HomeButton() {
const navigate = useNavigate();
return (
<button onClick={() => navigate('/home')}>
Go Home
</button>
);
}To replace the current entry in the history stack (similar to
history.replace()), pass an options object with
replace: true:
navigate('/home', { replace: true });