user13883454
user13883454

Reputation: 41

How can I prevent home elements from rendering on every page?

In my home class I have a Hello, every time I change tabs, the Hello always gets rendered. How can I prevent this? I did not include any field of Hello in other tabs, this is quite weird.

import React, { Component } from 'react';

export default class Home extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <h3>Hello</h3>
    )
  }
}
import "bootstrap/dist/css/bootstrap.min.css";

import {BrowserRouter as Router,Route,} from 'react-router-dom'

import NotFound from './components/App/NotFound';

import Home from './components/Home/Home';

import Navbar from "./components/NavBar/Navbar";
import Login from "./components/Login/Login";
import SignUp from "./components/SignUp/SignUp";

function App() {
    return (
      <Router>
        <div className="container">
          <Navbar /> 
          <br/> 
            <Route path="/" component={Home}/>
            <Route path="/login" component={Login}/>
            <Route path="/signup" component={SignUp}/>
        </div>
      </Router>
    );
  }
  
export default App;

Image of the react app, the image

Upvotes: 1

Views: 40

Answers (2)

ezio4df
ezio4df

Reputation: 4195

Hey u may wanna do this,

<Route path="/" exact={true} component={Home}/>

the path / actually matches everything on the site, to prevent this you can use,

1: exact prop

<Route path="/" exact={true} component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/signup" component={SignUp}/>

2: Switch component

<Switch>
  <Route path="/" component={Home}/>
  <Route path="/login" component={Login}/>
  <Route path="/signup" component={SignUp}/>
</Switch>

Only one Route will be used. NOTE: You have to keep the order maintained

Upvotes: 1

Siddhant Varma
Siddhant Varma

Reputation: 594

The reason why this is happening is that you render all your routes together. You should either pass the exact prop inside the Route component for each Route

 <Route exact path="/signup" component={SignUp}/>

or render your routes inside the Switch tag.

  <Switch>
     <Route path="/" component={Home}/>
     <Route path="/login" component={Login}/>
     <Route path="/signup" component={SignUp}/>
</Switch>

Remember that the order of your routes is also important and you may want to render your root route at the end. For the latter, don't forget to import Switch from react-router-dom

Upvotes: 0

Related Questions