In React Router v5, creating a global history object allowed for convenient navigation outside of components. However, this behavior is not immediately apparent in v6.
One approach is to create a custom router that utilizes a custom history object and manages the navigation state. Inspired by the implementation of BrowserRouter in v6:
<code class="javascript">const CustomRouter = ({ history, ...props }) => { const [state, setState] = useState({ action: history.action, location: history.location, }); useLayoutEffect(() => history.listen(setState), [history]); return ( <Router {...props} location={state.location} navigationType={state.action} navigator={history} /> ); };</code>
By utilizing this custom router with a custom history object, it effectively proxies the history object and manages the navigation state.
Within the React application, you can then swap the default Router for the custom router:
<code class="javascript">export default function App() { return ( <CustomRouter history={history}> <div className="App"> <Routes> <Route path="/" element={<Home />} /> <Route path="/profile" element={<Profile />} /> </Routes> </div> </CustomRouter> ); }</code>
react-router-dom@6 introduced an 'unstable' HistoryRouter that allows for injection of a custom history library instance:
<code class="javascript">import { unstable_HistoryRouter as HistoryRouter } from 'react-router-dom'; import { createBrowserHistory } from 'history'; const history = createBrowserHistory({ window }); ReactDOM.render( <HistoryRouter history={history}> {/* The rest of your app goes here */} </HistoryRouter>, root );</code>
Note that this API is marked unstable and may require further refinement or dependency management considerations.
In RRDv6.4 with Data Routers, an 'unstable' navigate function is directly exposed by the router object:
<code class="javascript">import { createBrowserRouter } from 'react-router-dom'; const router = createBrowserRouter(...); ... router.navigate(targetPath, options);</code>
The above is the detailed content of How to Navigate Outside Components in React Router v6?. For more information, please follow other related articles on the PHP Chinese website!