I am using the latest version of react router. When I am using routes in my component, They are not rendering anything but When I remove the routes and use simply the component they are working fine. Not able to understand what is going wrong
This do not work and is not rendering anything on “/” or http://localhost:3000/
import React from "react"; import { BrowserRouter as Router, Route, Navigate } from "react-router-dom"; import Users from "./user/pages/Users"; function App() { return ( <Router> <Route path="/" exact> <Users /> </Route> <Navigate to="/" /> </Router> ); } export default App;
This is rendering and working fine.
import React from "react"; import { BrowserRouter as Router, Route, Navigate } from "react-router-dom"; import Users from "./user/pages/Users"; function App() { return <Users />; } export default App;
Advertisement
Answer
import React, {useState} from "react"; import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom"; import Users from "./user/pages/Users"; import Profiles from "./Profiles" // this is dummy function App() { const [state, setState] = useState(false) return ( <Router> <Routes> <Route path="/" element={<Users />}/> <Route path="/profiles" element={state ? <Profiles /> : <Navigate to="/" />} /> {/* so you redirect only if your state is false */} </Routes> </Router> ); } export default App;