'When I apply react router to my app, it stops showing all the content
I'm trying to create an app with react router, but when I try to apply the react router, it instantly stops showing all the content. I'm using V5 so Switch should work but it doesnt
Here is the code:
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
<>
<Router>
<Switch>
<Route exact path="/">
<Main />
</Route>
<Route exact path="/form">
<Form />
</Route>
</Switch>
</Router>
</>
);
Solution 1:[1]
You have setup your routes, but you aren't rendering any components.
With React Router V6, simply instansiate a React component inside the element prop on each Route:
...
export default function App() {
return (
<>
<Router>
<Switch>
<Route exact path="/" element={<Home />}>
<Main />
</Route>
<Route exact path="/form" element={<Form />}>
<Form />
</Route>
</Switch>
</Router>
</>
);
If you haven't already, I'd advice encapsulating each route into its own component to make this easier.
Solution 2:[2]
You need to first go to the index.js or main.jsx file and wrap your App component with BrowserRouter> component.
<BrowserRouter>
<App />
</BrowserRouter>
or you can create routes here as the example below
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="compOne" element={<Component1 />} />
<Route path="compTwo" element={<Component2 />} />
</Routes>
</BrowserRouter>
Now you can use routes by using Navlink or Link components.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sam |
| Solution 2 | LearnTechWithFun |
