REACT JS

How to redirect to another page after login in React JS

How to redirect to another page after login in React JS

When building a web application, redirecting users to different pages after they log in is a common requirement. This functionality enhances user experience by guiding users to the appropriate landing page based on their credentials or role. In this blog post, we will walk you through the steps to implement a redirect after login in a React application.

Prerequisites

Before diving into the code, ensure you have the following:

  1. A basic understanding of React JS.
  2. Node.js and npm installed on your machine.
  3. A React project set up. If you don’t have one, you can create it using Create React App:
   npx create-react-app login-redirect-demo
   cd login-redirect-demo
   npm start

Steps to Implement Redirect After Login

Step 1: Install React Router

To handle navigation and redirects, we’ll use React Router. Install it using npm:

npm install react-router-dom

Step 2: Set Up Routes

Create routes for your application in a Router component. In your App.js file, import necessary components from react-router-dom and define your routes:

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import Login from './Login';
import Dashboard from './Dashboard';

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

export default App;

Step 3: Create the Login Component

Next, create a Login component. This component will contain the login form and handle the login logic. In this example, we’ll simulate a login process and redirect the user to the Dashboard page upon successful login.

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

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

  const handleLogin = (event) => {
    event.preventDefault();

    // Simulate login process
    if (username === 'user' && password === 'password') {
      // Redirect to dashboard
      history.push('/dashboard');
    } else {
      alert('Invalid credentials');
    }
  };

  return (
    <div>
      <h2>Login</h2>
      <form onSubmit={handleLogin}>
        <div>
          <label>Username</label>
          <input
            type="text"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
          />
        </div>
        <div>
          <label>Password</label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </div>
        <button type="submit">Login</button>
      </form>
    </div>
  );
}

export default Login;

Step 4: Create the Dashboard Component

Create a simple Dashboard component to which the user will be redirected after login:

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

function Dashboard() {
  return <h2>Welcome to the Dashboard!</h2>;
}

export default Dashboard;

Step 5: Create the Home Component

For completeness, let’s create a Home component as well:

// src/Home.js
import React from 'react';
import { Link } from 'react-router-dom';

function Home() {
  return (
    <div>
      <h2>Home Page</h2>
      <Link to="/login">Login</Link>
    </div>
  );
}

export default Home;

Step 6: Run the Application

Run your application using:

npm start

You should see the Home page with a link to the login page. After logging in with the correct credentials (user and password), you should be redirected to the Dashboard.

Conclusion

Implementing a redirect after login in a React application involves using React Router to manage navigation and the useHistory hook to programmatically navigate to different routes. This simple example demonstrates how to set up routes, create a login form, and handle redirection based on user authentication.

Feel free to expand on this basic setup by integrating actual authentication logic, role-based redirects, and more complex navigation patterns as required by your application. Happy coding!

You may also like

REACT JS

How to do a for loop in React JS

React.js is a popular JavaScript library for building user interfaces, and it's known for its component-based architecture. While React encourages
How to redirect to another page after login in React JS
REACT JS

How to fetch data from local JSON file in React JS

Fetching data is a fundamental part of building dynamic web applications. Often, you might need to load data from a
en_USEnglish