Reputation: 41
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,
Upvotes: 1
Views: 40
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,
exact
prop<Route path="/" exact={true} component={Home}/>
<Route path="/login" component={Login}/>
<Route path="/signup" component={SignUp}/>
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
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