Home >Web Front-end >JS Tutorial >How can I navigate outside components in React Router v6?
In React Router v5, creating a global history object and passing it to the router enabled navigation outside components. However, this approach is no longer possible in v6.
To address this, you can create a custom router that instantiates the history state like React Router v6 routers. For example, for a BrowserRouter:
<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>
This proxies the custom history object into the Router and manages the navigation state. Replace the original Router with this custom one:
<code class="javascript">export default function App() { return ( <CustomRouter history={history}> <div className="App"> {/* ... */} </div> </CustomRouter> ); }</code>
React Router v6 also introduces unstable_HistoryRouter for accessing the history 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}> {/* ... */} </HistoryRouter>, root );</code>
This exports an instance of the history library, which can be accessed outside of React components.
In React Router v6.4 , a new "unattached" navigation method is available for Data routers:
<code class="javascript">import { createBrowserRouter } from 'react-router-dom'; const router = createBrowserRouter(...); router.navigate(targetPath, options);</code>
This method provides access to the router's navigate function directly, allowing for navigation outside components with Data routers.
The above is the detailed content of How can I navigate outside components in React Router v6?. For more information, please follow other related articles on the PHP Chinese website!