Home > Mobile >  React Router Link not loading the page
React Router Link not loading the page

Time:05-08

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

CodePudding user response:

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/App.tsx

CodePudding user response:

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

  • Related