Navigation in React Router
Redirect specific URLs using Navigation
Navigate in React
In order to do redirect the page we can use useNavigate() hook.
index.js
import { createRoot } from “react-dom/client”;
import { BrowserRouter } from “react-router-dom”;
import “./index.css”;
import App from “./App”;
const rootElement = document.getElementById(“root”);
const root = createRoot(rootElement);
root.render(
<BrowserRouter>
<App />
</BrowserRouter>,
);
App.js
import { Routes, Route } from “react-router-dom”;
import “./index.css”;
import Navbar from “./components/navbar/Navbar”;
import Home from “./pages/home/Home”;
import Posts from “./components/Posts”;
const App = () => {
return (
<>
<Routes>
<Route path=”/” element={<Home />} />
<Route path=”/navbar” element={<Navbar />} />
<Route path=”/posts/*” element={<Posts />} />
</Routes>
</>
);
};
export default App;
We can also have nested routes and we can display something specific on a page if it's a certain route.
Since I am already within the post route here, <Route path=”/name/sagar” /> when I say /show I actually mean it to display /name/sagar like it is written within the post route.
Modify App.js: we are adding the *
<Route path=”/posts/*” element={<Posts />} />
Posts.jsx
import { Navigate, Route, Routes, useNavigate } from “react-router-dom”;
const Posts = () => {
//say dummy status coming from the server
const status = 200;
const navigate = useNavigate();
const onClick = () => {
console.log(“hello”);
navigate(“/about”);
};
//if page is not found we will redirect to page 404 not found.
if (status === 404) {
return <Navigate to=”/notfound” />;
}
return (
<div>
<button onClick={onClick}>click me</button>
<Routes>
<Route path=”/name/sagar” element={<h1>Hello Sagar</h1>}/>
</Routes>
</div>
);
};
export default Posts;