Search code examples
reactjsreact-routerreact-link

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

  • 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