Skip to content

React Router: How to easily secure certain routes

React Router: How to easily secure certain routes

React Router is a popular routing library for React applications that allows developers to handle client-side routing within their React applications. It enables developers to create dynamic and responsive applications by allowing them to change the contents of the application based on the current URL.

React Router

React Router provides a set of components that can be used to define the application’s routing. The most commonly used components include:

  1. BrowserRouter – Used to provide routing functionality to the application
  2. Route – Used to define a mapping between a URL and a component
  3. Switch – Renders only the first matching Route or Redirect within its child components
  4. Redirect – Used to redirect to a specified URL
  5. Link – Used to navigate between different pages of the application
  6. NavLink – Similar to Link, but allows for the styling of the active link

React Router also allows for the passing of parameters through the URL, which can be accessed in the component using the useParams hook.

Below is an example of how you could use React Router with authorization to control access to certain routes:

import React, { useState } from 'react';
import { BrowserRouter, Switch, Route, Link, Redirect } from 'react-router-dom';

const Home = () => <h1>Welcome to the home page!</h1>;
const About = () => <h1>Learn more about us!</h1>;
const Login = ({ isLoggedIn, handleLogin }) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleUsernameChange = event => setUsername(event.target.value);
  const handlePasswordChange = event => setPassword(event.target.value);
  const handleSubmit = event => {
    event.preventDefault();
    handleLogin(username, password);
  };

  if (isLoggedIn) {
    return <Redirect to="/" />;
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Username:
        <input type="text" value={username} onChange={handleUsernameChange} />
      </label>
      <label>
        Password:
        <input type="password" value={password} onChange={handlePasswordChange} />
      </label>
      <button type="submit">Login</button>
    </form>
  );
};

const App = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  const handleLogin = (username, password) => {
    // Here you would normally authenticate the user and set isLoggedIn to true if the credentials are valid
    setIsLoggedIn(true);
  };

  return (
    <BrowserRouter>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
        </ul>
        {isLoggedIn ? (
          <button onClick={() => setIsLoggedIn(false)}>Logout</button>
        ) : (
          <Link to="/login">Login</Link>
        )}
      </nav>
      <Switch>
        <Route exact path="/">
          {isLoggedIn ? <Home /> : <Redirect to="/login" />}
        </Route>
        <Route path="/about">
          {isLoggedIn ? <About /> : <Redirect to="/login" />}
        </Route>
        <Route path="/login">
          <Login isLoggedIn={isLoggedIn} handleLogin={handleLogin} />
        </Route>
      </Switch>
    </BrowserRouter>
  );
};

export default App;

In this example, we’ve added a Login component that allows users to log in with a username and password. When the user submits the form, the handleLogin function is called, which sets the isLoggedIn state to true.

We’ve also added logic to the App component that controls access to certain routes based on the isLoggedIn state. If the user is not logged in, they will be redirected to the login page if they try to access the Home or About pages. If the user is logged in, they will be able to access all the pages.

Additionally, we’ve added a logout button that sets the isLoggedIn state back to false when clicked.

This is just a basic example, but you can use this as a starting point and add more complex authorization logic as needed. Overall, React Router simplifies the process of implementing routing within a React application, making it easier to create a single-page application with multiple views.

Further Reading

Vite React: How to achieve faster and better build

Please share