I have the following App.js:
function App() {
return (
<div className="App">
<Header></Header>
<HomePage></HomePage>
</div>
);
}
Anyone accessing the website should see the homepage first by default.
I have a navigation menu with the following routing information:
<Router>
<Switch>
<Route path='/login' component={Authentication} />
</Switch>
</Router>
When I click on the login menu link, the authentication page loads, but I can also see the homepage below when scroll down in the browser. How do I load only the page referenced in the router?
SOLUTION:
Added the following route to the router
<Route exact path='/' component={Home} />
To start with routing , first install the routing package − Once we create the create the project with create-react-app, we will see there is only one html file and that is index.html and a single component named as App Now, we will create two more components AboutUs.jsx and ContactUs.jsx We have now three components App, AboutUs, ContactUs.jsx
For few scenarios, developer may want to skip react-router from handling some urls and rather refresh from server. Example url - '/help' may be different section than Single page app using React+router. Clicking '/help' should then skip react-router from matching and transitioning to NotFound, rather should be rendered from server-side.
Before React Router v4, the routing in react was static but after v4 update its dynamic. In single page applications, we have only one page index.html and different components which gets displayed based on routes.
Different path in Route
shows different page (the component attribute in Route
), here is a demo and react-router docs maybe helps you. Good luck!
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
</ul>
</nav>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/users">
<Users />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Users() {
return <h2>Users</h2>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With