How to achieve conditional routing in React

Last updated on Jun 11, 2021 by Suraj Sharma



In this tutorial, you will learn about how you can set up a conditional routing using react-router-dom library.


How to conditionally route between components


Consider you have a user flow where a user after logged into your react app, hits the /login route.


As the user is already logged-in, the user should always get redirect to the /home instead of the login page and vice versa when the user is not logged in.


To get started, let’s create a <Login /> component, a <Home /> component, and a <Routes /> component, which will contain a logic to conditionally route between the components.


// ./Login.jsx

import React from 'react';

const Login = () => {
  
  const [formValue, setformValue] = React.useState({
    email: '',
    password: ''
  });

  const handleSubmit = (event) => {
    event.preventDefault();
    const { email, password } = formValue;
    if (email && email.trim() && password && password.trim()) {
      localStorage.setItem('token', '123');
    }
  }

  const handleChange = (event) => {
    setformValue({
      ...formValue,
      [event.target.name]: event.target.value
    })
  }

  return (
    <form onSubmit={handleSubmit}>
      <p>Login to Get Started</p>
      <input
        type="email"
        name="email"
        placeholder="enter an email"
        value={formValue.email}
        onChange={handleChange}
      />
      <input
        type="password"
        name="password"
        placeholder="enter a password"
        value={formValue.password}
        onChange={handleChange}
      />
      <button
        color="primary"
        type="submit"
      >
        Login
      </button>
    </form>
  )
};

export default Login;

// ./Home.jsx

import React from 'react'

const HomePage = () => {
  return <p>Welcome, User</p>
}

export default HomePage;

// ./Routes.jsx

import React from 'react';
import PrivateRoutes from './PrivateRoute';
import PublicRoutes from './PublicRoute';

const AuthorizationContext  = React.createContext();

const Routes = () => {
  const token = localStorage.getItem('token');

  // conditionally route based on the token value

  return (
    <AuthorizationContext.Provider value={token}>
      {!!token ? <PrivateRoute /> : <PublicRoute />}
    </AuthorizationContext.Provider>
  )
}

export default Routes;

We have used the browser's localStorage to store a dummy token once the user successfully logs into the app.


To make the token globally accessible to the components we have used the AuthorizationContext context API.


Finally, we have imported a <PrivateRoutes />, which contains the private routes, if the user tries to hit the '/login' route, he/she will be redirected to the home page



Create a Private Route component


// ./PrivateRoute.jsx

import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import LoginPage from './LoginPage';
import HomePage from './Home';

const PrivateRoute = () => {
  
  return (
    <Switch>
      <Route path="/private" component={HomePage} />
      <Redirect to='/private' />
    </Switch>
  )
}

export default PrivateRoute;


Create a Public Route component


// ./PublicRoute.jsx

import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import LoginPage from './LoginPage';
import HomePage from './HomePage';

const PublicRoute = () => {
  
  return (
    <Switch>
      <Route path="/login" component={LoginPage} />
      <Redirect to='/' />
    </Switch>
  )
}

export default PublicRoute;


Conclusion


In this tutorial, we have learnt how we can use <PrivateRoute /> and` components to define our private routes and public routes respectively.

Moreover, we have also defined a React context API to globally share the authentication state across our application.

We have used the localStorage to store the authentication token, read the token from the localStorage and redirect the user to ‘/private’ route.



Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.