How do you redirect a user to a different route in React Router

0 votes
Can i know How do you redirect a user to a different route in React Router?
Feb 22 in Node-js by Nidhi
• 16,020 points
100 views

1 answer to this question.

0 votes

Redirecting a User in React Router

1. Using <Navigate> (React Router v6)

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

const Login = () => {

  const isAuthenticated = true; // Example condition

  if (isAuthenticated) {

    return <Navigate to="/dashboard" replace />;

  }

  return <h1>Login Page</h1>;

};

export default Login;

2. Using useNavigate Hook (React Router v6)

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

const Home = () => {

  const navigate = useNavigate();

  return (

    <button onClick={() => navigate("/dashboard")}>Go to Dashboard</button>

  );

};

export default Home;

3. Redirect in useEffect (React Router v6)

import { useEffect } from "react";

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

const ProtectedPage = () => {

  const navigate = useNavigate();

  useEffect(() => {

    navigate("/login"); // Redirects to login if unauthorized

  }, [navigate]);

  return <h1>Protected Content</h1>;

};

export default ProtectedPage;

answered Feb 23 by Kavya

Related Questions In Node-js

0 votes
1 answer

How can you programmatically navigate to a different route in React Router v5?

In React Router v5, you can programmatically ...READ MORE

answered Apr 17 in Node-js by anonymous
36 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to pass parameters with react-router?

Passing Parameters with React Router 1. Define a ...READ MORE

answered Feb 23 in Node-js by Kavya
175 views
0 votes
1 answer

What is the use of Switch in React Router?

In React Router v5, <Switch> is used ...READ MORE

answered Feb 23 in Node-js by Kavya
106 views
0 votes
1 answer

How do you create protected routes in React?

Creating Protected Routes in React (React Router ...READ MORE

answered Feb 23 in Node-js by Kavya
147 views
0 votes
1 answer

What is the difference between BrowserRouter and createBrowserRouter?

Feature BrowserRouter (React Router v5 & v6) createBrowserRouter (React ...READ MORE

answered Feb 23 in Node-js by Kavya
208 views
0 votes
1 answer
0 votes
1 answer

How do you model a many-to-many relationship in MongoDB with an example?

In MongoDB, a many-to-many relationship can be ...READ MORE

answered Feb 23 in Node-js by Kavya
134 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP