'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!



Solution 1:[1]

In my case I needed access to the history object before first render, so I ended up writing custom component around Router based on the BrowserRouter implementation that would allow me to pass in history through props.

See https://github.com/remix-run/react-router/discussions/8241#discussioncomment-1677474 for code.

Edit: As of react-router-dom v6.1.0 HistoryRouter is part of its implementation so you can just directly do:

import {unstable_HistoryRouter as HistoryRouter} from 'react-router-dom'
import {createBrowserHistory} from 'history'

const history = createBrowserHistory()

<HistoryRouter history={history} />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1