Redirects in React

In this lesson, we’ll look at how to use the react-router-dom package to redirects to another page in ReactJS. Building single page applications uses the free and open source front-end library ReactJS.

React-router-dom:

ReactJS library that makes it possible to integrate dynamic routing into a website. 

We need to install the react-router-dom package in our project before we can utilize it. One of the aforementioned commands can be used to achieve this in our terminal:

$ npm i react-router-dom

Component Navigation and Redirect

In earlier iterations of the react-router-dom package, the Redirect component was typically used to rapidly do redirects by simply importing the component from react-router-dom and then making use of the component by specifying the to prop, which specifies the page you want to redirect to.

The route we wish to redirect to must be passed to the <Redirect> component before it can be rendered. The react-router-dom library has it loaded and ready to use.

import { Redirect } from "react-router-dom";

state = { redirect: null };
render() {
  if (this.state.redirect) {
    return <Redirect to={this.state.redirect} />
  }
  return(
  // Your Code goes here
  )
}

You may easily alter the state of the component to re-render it whenever you want to redirect to a different path, rendering the <Redirect> component.

this.setState({ redirect: "/Home" });

useHistory Hook:

One of React Router’s most well-liked hooks is this one. You can use it to get the history instance that React Router uses. You can send visitors to another page by using the history instance. React Router uses a stack to record all the items visited by the user in the history instance it creates.

import { useHistory } from "react-router-dom";

function App() {
  let history = useHistory();
}



The.push() technique allows us to reroute to any route we desire.

history.push('/Home')

History prop:

Every component that is the <Route> component’s immediate child is given a history object as a prop. This is the same history  that stores the history of a React Router session. Thus, we can use its features to find the necessary pathways.

this.props.history.push("/first");


The lack of a history prop in components that are not the Route> component’s immediate children is a common issue we can run into in this situation. Utilizing the withRouter function, this is a simple problem to tackle. Here’s a brief summary of the Development of a login display screen with React and Bootstrap, that you don’t want to miss out.

withRouter:

The react-router-dom package has a function called withRouter that enables us to access the history prop in components that are not direct descendants of the components.

import { withRouter } from "react-router-dom";



createHistory

The techniques we learnt before can handle the majority of the situations we’ll ever face when developing a react app, so why use this fourth technique?

Every time we need to redirect from, let’s use a redux action as an example, we always have to pass history to the action, increasing the number of parameters unnecessarily. Thus, this technique can be applied to produce a cleaner code.

This function creates a custom history object that may be imported into other files to reroute traffic.

import { Router } from "react-router-dom";
import history from "./utils/history";

function App(){
  return(
    <Router history={history}>
    // Your Routes go here
    <Router>
  )
}





If we want to redirect from a different file, we may import this history instance from that one.

import history from "./utils/history";

history.push("/somePath");



Examples:

import {Routes, Route, useNavigate} from 'react-router-dom';

export default function App() {
  const navigate = useNavigate();

  const navigateToContacts = () => {
    navigate('/contacts');
  };

  const navigateHome = () => {
    navigate('/');
  };

  return (
    <div>
      <div>
        <button onClick={navigateHome}>Home</button>
        <hr />
        <button onClick={navigateToContacts}>Contacts</button>

        <Routes>
          <Route path="/contacts" element={<Contacts />} />
          <Route path="/" element={<Home />} />
        </Routes>
      </div>
    </div>
  );
}

function Home() {
  return <h2>Home</h2>;
}

function Contacts() {
  return <h2>Contacts</h2>;
}



Conclusion: 

By this point, I hope you have a good understanding of how client-side routing functions in general and how to use the React Router package to implement routing in React.

You gained knowledge of the fundamental React Router elements, such as Route, withRouter, Link, and others, as well as more sophisticated ideas, such as authenticated routes, that are necessary to develop an application.

One Comment “Redirects in React”

  • user

    says:

    test

Leave a Comment

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

Let's Get in Touch

Read our customer feedback

Please fill in the form below.


    To top