I'm following a tutorial using the react-router-dom
React library.
The problem I have is that my navigation header is displayed regardless of which URL I write in the address bar after localhost:3000
, (for ex localhost:3000/dflkjfhdlkfjhdf
will actually display the navigation header instead of saying it's an invalid URL)
index.js:
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
App.js:
function App() {
return (
<div>
<MainNavigation />
<Routes>
<Route path="/" element={<AllMeetupsPage />} />
<Route path="/new-meetup" element={<NewMeetupPage />} />
<Route path="/favorites" element={<FavoritesPage />} />
</Routes>
</div>
);
}
MainNavigation.js:
function MainNavigation() {
return (
<header className={classes.header}>
<div className={classes.logo}> React Meetups </div>
<nav>
<ul>
<li>
<Link to="/">All Meetups</Link>
</li>
<li>
<Link to="/new-meetup">Add New Meetup</Link>
</li>
<li>
<Link to="/favorites">My Favorites</Link>
</li>
</ul>
</nav>
</header>
);
}
with all the necessary import statements.
I think the problem might be that <MainNavigation />
is in the App()
function which is wrapped in <BrowserRouter>
tags in index.js.
However I don't understand the mechanism or how to prevent this from happening (or whether it matters in the first place since it probably won't happen once I deploy the app).
EDIT: To be clear I want the <MainNavigation />
component in App.js because I want that component displayed on every page, but maybe not on localhost:3000/dfkjldfkjh
CodePudding user response:
Kindly checkout the solution on this link
https://stackoverflow.com/a/56828778/12482704
See how it was solved
CodePudding user response:
The issue it seems is that your app doesn't do anything to "avoid" URL paths it doesn't exclusively have a match for. With a path like "/dfkjldfkjh"
the Routes
component will check for a match, and not find any, and correctly not return any matched routed component to render. The MainNavigation
will still render regardless of any route path matching.
The solution then is to add a redirect route to your app to handle any "unknown" paths and redirect the app back to a known, handled route.
<Route path="*" element={<Navigate to="/" replace />} />
Example:
import { Routes, Route, Navigation } from 'react-router-dom';
function App() {
return (
<div>
<MainNavigation />
<Routes>
<Route path="/" element={<AllMeetupsPage />} />
<Route path="/new-meetup" element={<NewMeetupPage />} />
<Route path="/favorites" element={<FavoritesPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</div>
);
}