Reactjs routing causing page render issues

Viewed 133

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} />
3 Answers

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>;
}

You have to add "exact path" keyword in the Route section like this: <Route exact path="/" component={Home} /> If you don't use "exact" it will render all the component which route contains "/".

Use exact for this issue.

    <Route exact path="/">
        <Home />
    </Route>
Related