'React Router Link not loading the page
I'm trying to redirect to page onclick of a button from my main page App.js, But my redirected page /SelectAirport does not seem to load. I think there might be something with the link path but I can't figure out how to fix it.
TLDR: The link changes but the content does not load.
App.js
function App() {
return(
<div>
<Button>
<Link to="./SelectAirport">Select Airport</Link>
</Button>
</div>
)
}
export default App;
Full Code here - https://codesandbox.io/s/boring-chihiro-zckfr5?file=/App.js:152-355
Solution 1:[1]
Use Routes and Route , inside of Route define your component and path for example path='/airports'
import { Button } from "@mui/material";
import React from "react";
import { NavLink } from "react-router-dom";
import SelectAirport from "./SelectAirport";
import {
Routes,
Route,
} from "react-router-dom";
function App() {
return(
<div>
<Button>
<NavLink to="/airports">Select Airport</NavLink>
</Button>
<Routes>
<Route path='/airports' element={<SelectAirport/>} />
</Routes>
</div>
)
}
export default App;
Sandbox example Working example
Solution 2:[2]
Where is your route? You have to first create a route for select-airport or something like that. Currently, you are just trying to load a component directly.
The route might look like this:
import SelectAirport from "./SelectAirport";
<Route path="select-airport" element={<SelectAirport />} />
After this, Link will start to work, and for your case this link should be something like:
<Link to="/select-airport">Select Airport</Link>
So, whenever, it hit select-airport, it will try to find the matching component via route and load that componet.
basic example can be found here. https://v5.reactrouter.com/web/example/basic (v5)
https://reactrouter.com/docs/en/v6/getting-started/overview (v6)
v6 code sample: https://stackblitz.com/github/remix-run/react-router/tree/main/examples/basic?file=src%2FApp.tsx
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 | Hakob Sargsyan |
| Solution 2 | Saroj Shrestha |
