How to redirect to another page after login in React JS

Cynthia

In a React.js application, one common requirement is to redirect users to a different page after they successfully log in. This can be achieved using React Router, a widely-used library for handling routing in React applications. In this blog post, we'll walk through the process of setting up a simple login page and implementing a redirection mechanism after login.

Prerequisites

Before we start, make sure you have the following prerequisites in place:

  1. Node.js and npm: Ensure that you have Node.js and npm (Node Package Manager) installed on your computer. You can download them from nodejs.org.

  2. React Project: You should have an existing React project or create a new one. You can create a new React app using Create React App or any other setup of your choice.

Step 1: Create a React App (If Needed)

If you don't have a React project, you can create one using Create React App. Open your terminal and run the following command:

npx create-react-app login-app

Replace login-app with your preferred project name.

Step 2: Install Dependencies

In your project directory, navigate to the newly created React app and install the required dependencies. You'll need react-router-dom for handling routing.

cd login-app
npm install react-router-dom --save

Step 3: Create Login and Dashboard Components

Let's create two components: Login.js and Dashboard.js. The Login component will represent the login page, and the Dashboard component will represent the page users should be redirected to after login.

In your src directory, create these two components:

Login.js:

// src/Login.js
import React, { useState } from "react";
import { useHistory } from "react-router-dom";

const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const history = useHistory();

  const handleLogin = () => {
    // Perform your authentication logic here
    // For this example, we'll consider it a success if the username is 'admin' and the password is 'password'
    if (username === "admin" && password === "password") {
      // Redirect to the Dashboard page after successful login
      history.push("/dashboard");
    } else {
      alert("Login failed. Please check your credentials.");
    }
  };

  return (
    <div>
      <h1>Login</h1>
      <input
        type="text"
        placeholder="Username"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button onClick={handleLogin}>Login</button>
    </div>
  );
};

export default Login;

Dashboard.js:

// src/Dashboard.js
import React from "react";

const Dashboard = () => {
  return (
    <div>
      <h1>Dashboard</h1>
      <p>Welcome to the Dashboard!</p>
    </div>
  );
};

export default Dashboard;

Step 4: Set Up Routes

Now, let's set up routes for the Login and Dashboard components. Open the src/App.js file and modify it as follows:

// src/App.js
import React from "react";
import "./App.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Login from "./Login";
import Dashboard from "./Dashboard";

function App() {
  return (
    <Router>
      <div className="App">
        <Switch>
          <Route exact path="/" component={Login} />
          <Route path="/dashboard" component={Dashboard} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;

We're using React Router to define two routes: one for the Login component (path '/') and one for the Dashboard component (path '/dashboard').

Step 5: Running the Application

Start your React application by running:

npm start

You should see the login page at the root URL ('/') of your application. Enter the username 'admin' and password 'password', and you'll be redirected to the dashboard page ('/dashboard') upon successful login.

Conclusion

In this blog post, we've created a simple login page and implemented redirection to a dashboard page after login in a React.js application. We used React Router to handle routing and the useHistory hook to programmatically navigate to the dashboard page upon successful login. You can extend this example by adding more complex authentication logic and customizing the login and dashboard components to fit your application's needs. Redirection is a fundamental part of user authentication and navigation in React applications, and React Router makes it easy to implement.