Redirection in web applications refers to the process of sending a user from one page or component to another. In the context of single-page applications (SPAs) built with React, client-side redirection allows you to change the view without refreshing the entire page. This enhances the user experience by providing seamless navigation between different parts of the application.
One of the most straightforward ways to achieve client-side redirection is through the Navigate component.
What is the Navigate Component?
The Navigate component is part of React Router and is used to programmatically redirect users to a different route. It can be especially useful for redirecting users after a form submission, an authentication check, or any event where you need to change the current URL based on user interaction.
Example
<!-- HTML generated using hilite.me --><div style="background: #ffffff; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"><span style="color: #000080; font-weight: bold">if</span> (isLoggedIn) {
<span style="color: #008800; font-style: italic">// Redirect to dashboard</span>
<span style="color: #000080; font-weight: bold">return</span> <Navigate to=<span style="color: #0000FF">"/dashboard"</span> />;
}
</pre></div>
Follow below step-by-step procedure to build the working application.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘client-side-redirection’.
Project structure looks like below.
Step 2: Navigate to the project directory and install react router dom by executing below commands.
cd client-side-redirection npm install react-router-dom
Step 3: Create pages folder in src folder and define Login and Welcome pages.
LoginPage.jsx
import React, { useState } from "react";
import { Navigate } from "react-router-dom";
const LoginPage = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const handleLogin = (e) => {
e.preventDefault();
// Simulate successful login
setIsLoggedIn(true);
};
if (isLoggedIn) {
// Redirect to welcome page
return <Navigate to="/welcome" />;
}
return (
<div>
<h2>Login Page</h2>
<form onSubmit={handleLogin}>
<p>
<label htmlFor="username">Enter Username : </label>
<input type="text" placeholder="Username" id="usernane" required />
</p>
<p>
<label htmlFor="password">Enter Password : </label>
<input type="password" placeholder="Password" required />
</p>
<button type="submit">Login</button>
</form>
</div>
);
};
export default LoginPage;
WelcomePage.jsx
export default function WelcomePage() {
return <>Welcome to the React World!!!!!!!!</>;
}
Step 4: Update App.jsx with below content.
App.jsx
import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import LoginPage from "./pages/LoginPage";
import WelcomePage from "./pages/WelcomePage";
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<LoginPage />} />
<Route path="/welcome" element={<WelcomePage />} />
</Routes>
</Router>
);
}
export default App;
Step 5: Update main.jsx with below content.
main.jsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
createRoot(document.getElementById("root")).render(
<StrictMode>
<App />
</StrictMode>
);
Step 6: Build and run the application by executing below commands.
cd client-side-redirection npm install npm run dev
Open the url ‘http://localhost:5173/’ in browser, you will see a login screen.
Enter some random username and password, click on Login button, you will be redirected to welcome page.
You can download the application from below link.
https://github.com/harikrishna553/frontend/tree/main/react/react-router/client-side-redirection
You can achieve the same behavior using useNavigate hook as well.
LoginPage.jsx
import React, { useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
const LoginPage = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const navigate = useNavigate(); // Correct: use the hook to get the navigate function
const handleLogin = (e) => {
e.preventDefault();
// Simulate successful login
setIsLoggedIn(true);
};
if (isLoggedIn) {
// Redirect to welcome page
//return <Navigate to="/welcome" />;
navigate("/welcome");
return;
}
return (
<div>
<h2>Login Page</h2>
<form onSubmit={handleLogin}>
<p>
<label htmlFor="username">Enter Username : </label>
<input type="text" placeholder="Username" id="usernane" required />
</p>
<p>
<label htmlFor="password">Enter Password : </label>
<input type="password" placeholder="Password" required />
</p>
<button type="submit">Login</button>
</form>
</div>
);
};
export default LoginPage;
No comments:
Post a Comment