Home >Web Front-end >JS Tutorial >How can I navigate outside components in React Router v6?

How can I navigate outside components in React Router v6?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 18:58:30674browse

How can I navigate outside components in React Router v6?

Navigating 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.

Custom Router Approach

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>

HistoryRouter

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.

Data Routers

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn