Route is not working i am a beginner of react.when i type the urls on the browser text is not displaying.what i tried so far i attached the below. i created the pages inside pages folder.
import Index from "./pages/Index";
import Login from "./pages/Login";
import Product from "./pages/Product";
import Register from "./pages/Register";
import {BrowserRouter,Route} from 'react-router-dom';
function App() {
return (
<div>
<BrowserRouter>
<Route path = "/">
<Index/>
</Route>
<Route path = "/login">
<Login/>
</Route>
<Route path = "/product">
<Product/>
</Route>
<Route path = "/register">
<Register/>
</Route>
</BrowserRouter>
</div>
);
}
export default App;
CodePudding user response:
You need to wrap all your routes inside Routes component. It's part of the react-router-dom
import Index from "./pages/Index";
import Login from "./pages/Login";
import Product from "./pages/Product";
import Register from "./pages/Register";
import {BrowserRouter,Routes,Route} from 'react-router-dom';
function App() {
return (
<div>
<BrowserRouter>
<Routes>
<Route path = "/" element={<Index />} />
<Route path = "/login" element={<Login />} />
<Route path = "/product" element={<Product />} />
<Route path = "/register" element={<Register/>} />
</Routes>
</BrowserRouter>
</div>
)}
export default App;
CodePudding user response:
Wrap all route in routes like this
function App() {
return (
<HashRouter>
<Routes>
<Route path="/" element={<Index/>} />
<Route path="/login" element={<Login/>} />
</Routes>
</HashRouter>
)
}
CodePudding user response:
Each Route shows the element you specify in its props using the element
prop.
Try this:
import Index from "./pages/Index";
import Login from "./pages/Login";
import Product from "./pages/Product";
import Register from "./pages/Register";
import {BrowserRouter,Route} from 'react-router-dom';
function App() {
return (
<div>
<BrowserRouter>
<Route path='/'>
<Route index element={<Index/>} />
<Route path="login" element={<Login/>} />
<Route path="product" element={<Product/>} />
<Route path="register" element={<Register/>} />
</Route>
</BrowserRouter>
</div>
);
}
export default App;
Extra context:
What this does is that you specify a home route at the path /
and all other routes are children of this home route.
The index property in the first nested route is used to tell the program this is the index page of the parent.
CodePudding user response:
You would need to pass the element prop where the path should direct to in the Routes tag. You can find documentation here.
This should work:
<Route index element={<Index/>}/>
<Route path="login" element={<Login/>}/>
<Route path="product" element={<Product/>}/>
<Route path="register" element={<Register/>}/>