reactjstypescriptreact-routerreact-router-dom

Alternative of the old CreateBrowserHistory() function in React Router v6


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?


Solution

  • In version 6, use useNavigate as below:

    let navigate = useNavigate()
    
    navigate('/not-found')
    

    this hook cannot be called at the top level, so you can pass it to navigate function to the function where you wanna call it.