React router navigate outside component

In this tutorial, we’ll learn how React routers navigate outside components in react. In a previous tutorial, we learned how to implement react-router in react 18.

I have faced an issue of how to navigate outside of the component. In our case, we are navigating in the action creator file in react application.

React router navigate outside component
React router navigate outside component

Example of React router navigate outside component

I don’t know if this approach is the best way of implementing react route navigation outside of the component. An example works correctly in react function component but I don’t have any ideas whether it works on react typescript. As I’m in a react learning stage, if any one of you guys knows a better approach, then, please leave a message in the comments.

First, we need to install the history library in our react project.

npm i history --save

The history library lets you easily manage session history anywhere JavaScript runs. A history object abstracts away the differences in various environments and provides a minimal API that lets you manage the history stack, navigate, and persist state between sessions.

Step 1: Create CustomRouter and history object

Let’s first create CustomRouter in src/customRoutes/CustomRoutes.j to implement React router navigate outside component

import React from 'react';
import { Router } from 'react-router-dom';

const CustomRouter = ({ basename, children, history }) => {
  const [state, setState] = React.useState({
    action: history.action,
    location: history.location,
  });

  React.useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      basename={basename}
      children={children}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};

export default CustomRouter;

Browser router internally creates and maintains the history object and in this example, we are not allowing the react-router to create the history object. We are going to create the history object by ourselves. Any time we can get access to our history object and we can import the history object.

We are no longer going to create a browser router object as our top component hierarchy instead we are going to create a plain router. Let’s create a history object in src/src/customRoutes/history.js

import { createBrowserHistory } from 'history';
export default createBrowserHistory();

We get createBrowserHistory from the history library.

Step 2: Replace BrowserRouter with the plain router

We have kept separate files for this history object that is responsible for navigating from the actionCreator file to the component. Let replace BrowserRouter with a plain router in the App.js

import React from 'react';
import { Routes, Route } from 'react-router-dom';
import history from '../customRoutes/history';
import CustomRouter from '../customRoutes/CustomRoutes';
// ... 

const App = () => {
  return (
    <div className='ui container'>
      <CustomRouter history={history}>
        <div>
          <Header />
          <Routes>
            <Route path='/' exact element={<Home />} />
            <Route path='/posts/new' exact element={<PostCreate />} />
            <Route path='/posts/edit/:id' exact element={<PostEdit />} />
            // .... more routes
          </Routes>
        </div>
      </CustomRouter>
    </div>
  );
};
export default App;

We need to import both history objects and custom routes in App.js and replace BrowserRoutes with our custom routes and pass history as props.

Step 3: Use a custom route outside of the component

Once we have our custom history object, we need to import it into our action creator file. Let add src/actions/index.js

import posts from '../apis/posts';
import history from '../customRoutes/history';

.....

export const editPost = (id, formValues) => async (dispatch) => {
  const response = await posts.patch(`/posts/${id}`, formValues);

  dispatch({ type: EDIT_POST, payload: response.data });
  history.push('/');
};

We used the push function to navigate around the different components. In push, we pass the path of the component where we want to navigate and in our case, we want to navigate to the root or home page.

Conclusion
In this article, we have learned React routers navigate outside components in React 18 and we had demonstrated an example of it.

Related Post

  1. How to implement React routing using react-router-dom 6?
  2. When and how to use React Context API?
  3. Best react color picker and how to implement it .?

Spread the love

Leave a Comment

Your email address will not be published.

Scroll to Top