Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to navigate outside of react component using react router 6

Right now I have an History module, that let me use the history even outside of react component:

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

Then I use this history in App.jsx directly

import { Router } from 'react-router-dom';
...
<Router history={history}>...</Router>

I can import and use the same history object everywhere. Even in custom helpers outside of any react components.

How could this work in react router 6?

Since history is replaced with navigate, I don't see any solution yet online.

I know it is still beta, but I would like to check on it in advance.

Thanks for any ideas!

like image 460
bukso Avatar asked Jul 15 '21 19:07

bukso


People also ask

How do I navigate with react router?

There are two ways to programmatically navigate with React Router - <Navigate /> and navigate() . You can get access to Navigate by importing it from the react-router-dom package and you can get access to navigate by using the custom useNavigate Hook.


1 Answers

I ended up with following solutions:

At first, react-router-dom 6 has navigate and not history. It is better to use navigate for the navigation trough the routes:

I create and fix my History object, so that it can continue work with 'push' and that I don't need big rework:

const History = {
  navigate: null,
  push: (page, ...rest) => History.navigate(page, ...rest),
};

export default History;

Then I made my own Component that set the navigation:

import { useNavigate } from 'react-router-dom';

const NavigateSetter = () => {
  History.navigate = useNavigate();

  return null;
};

Then while defining the default router, I place as a child the setter:

import { BrowserRouter } from 'react-router-dom';

<BrowserRouter>
    <NavigateSetter />
    <App />
</BrowserRouter>

After that you can use everywhere History.push or History.navigate with the default react-router-dom's navigate API.

like image 174
bukso Avatar answered Oct 17 '22 10:10

bukso