Navigate Component
The Navigate Component in react router is used for programmatic navigation within the application. It allows developer to trigger navigation imperatively based on certain conditions or events, rather than user interaction like clicks.
Key Features of navigate:
Usage:
Navigate is used to trigger navigation based on programmatic logic within application.
Props:
Similar to Link, the to prop is required and specifies the destination router or URL that the link should navigate to. Additional prop replace can be used to control navigation behavior.
// index.js file
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import { getAuth, onAuthStateChanged } from "firebase/auth";
import app from "./firbaseConfig";
import App from "./App";
const auth = getAuth(app);
const isAuthenticated = () => {
return new Promise((resolve, reject) => {
onAuthStateChanged(
auth,
(user) => {
if (user) {
// User is logged in
resolve(true);
console.log(user);
} else {
// User is not logged in
resolve(false);
console.log(user);
}
},
(error) => {
// An error occurred while checking authentication state
reject(error);
}
);
});
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App isAuthenticated={isAuthenticated} />
</React.StrictMode>
);
//app.jsx file
import Navbar from "./components/Navbar/Navbar";
import "./App.css";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import Home from "./pages/Home";
import Login from "./pages/Login";
import Signup from "./pages/Signup";
import Dashboard from "./pages/Dashboard";
const App = ({ isAuthenticated }) => {
return (
<BrowserRouter>
<div className="app">
<Navbar />
<Routes>
<Route path="/" element={<Home />} exact />
<Route path="/login" element={<Login />} />
<Route path="/signup" element={<Signup />} />
<Route
path="/dashboard"
element={
isAuthenticated ? <Dashboard /> : <Navigate to={"/login"} />
}
/>
</Routes>
</div>
</BrowserRouter>
);
};
export default App;
Output:
If user is Logged in then Dashboard Page automatically render otherwise user will navigate to login page.
Difference between Link and Navigate Component in React Router
In this article, we’ll delve into the intricacies of two fundamental components within the widely acclaimed React Router Dom Library a Link and Navigate. As the backbone of many react applications, these components play pivotal roles in facilitating seamless navigation and routing.
We’ll explore their respective functionalities, and use cases and most importantly, dissect the key differences between them. By the end of this article, you’ll have a comprehensive understanding of how to leverage Link and Navigate effectively in your React Router Dom-powered project.
Table of Content
- Link Component
- Navigate Component
- Difference between Link and Navigate
- Conclusion