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
• 11,580 points
46 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 do I redirect to a previous page in react?

You can use the useNavigate hook from ...READ MORE

answered Dec 31, 2024 in Node-js by Navya
82 views
0 votes
1 answer

How do you implement breadcrumbs in a React-Router app?

Breadcrumbs help users navigate by showing the ...READ MORE

answered Feb 24 in Node-js by Kavya
70 views
0 votes
1 answer

How do you handle scroll restoration in a React-Router app?

By default, React Router does not restore ...READ MORE

answered Feb 24 in Node-js by Kavya
83 views
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
90 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
47 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
76 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
86 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
67 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