Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

React Router navigate outside component

React router navigate outside component

In this tutorial, we’ll learn how React router navigate outside components in react like navigating from actionCreator to component. 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 and we want to navigate from action creator to component root page.

React router navigate outside component
React router navigate outside component

Example of React Router navigate outside component

We can easily navigated around React component with use of Link component. But we can’t use Link component from react-router-dom to React router navigate outside components.

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 component in src/customRoutes/CustomRoutes.js 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 used 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 or any other file which is outside of component. 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 router navigate outside component in React 18 and we had demonstrated an example of it. I hope you had learned something, if so then please share it with others and on social networks, this will encourage me to add more content. Follow me on my GitHub collection, I had code on Angular, react and Ionic framework.

Related Post

  1. Guide to Using and Creating React material UI grid.
  2. React material UI App Bar in detail with examples
  3. How to implement React table and its component?
  4. When and how to use React Context API?
  5. React Axios for HTTP method with REST API
  6. React router navigate outside component.
  7. How to implement React routing using react-router-dom?
  8. Best react color picker and how to implement it .?
React Router navigate outside component

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top