1

I want to push a new route in history of my app, and as you know, the UseHistory() hook and CreateBrowserHistory() function (to create a user-defined history) have been removed from new version of 6. I know that I can use UseNavigate hook and do this work with Navigate() function, but this hook cannot be called at the top level and must be called in a React function component. Codes below show how we could do this with React Router version 5.1:

Passing the history to the parent component and exporting the same history object for using it anywhere in Application:

import React from 'react'
import { Router } from 'react-router-dom'
import { createBrowserHistory } from 'history' // which comes along with React-Router

export const history = createBrowserHistory();

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)
root.render(
    <Router history={history}>
        <App />
    </Router>
)

Using the exported history object in another place of Application at the top level:

switch (status) {
    case 404:
        history.push('/not-found');
        break

if I want to do this at the top level in the new version of 6, What do you recommend?

MJDevelops
  • 39
  • 3
  • 1
    Does this help answer your question? https://stackoverflow.com/questions/69953377/react-router-v6-how-to-use-navigate-redirection-in-axios-interceptor/70012117#70012117 or https://stackoverflow.com/questions/69871987/react-router-v6-navigate-outside-of-components/70000286#70000286 – Drew Reese Dec 29 '22 at 09:18
  • 1
    Does this answer your question? [React router v6 how to use \`navigate\` redirection in axios interceptor](https://stackoverflow.com/questions/69953377/react-router-v6-how-to-use-navigate-redirection-in-axios-interceptor) – jonrsharpe Dec 29 '22 at 09:19
  • @jonrsharpe actually no – MJDevelops Dec 29 '22 at 09:52
  • 1
    Then [edit] the question to reflect what you've learned from those resources and what problem you're still facing. – jonrsharpe Dec 29 '22 at 09:53

0 Answers0