Reputation: 1153
Im not too experienced with react and I have a question. I wanted to have a component that has a nav bar and based on what is clicked-that component is rendered - BUT where the navbar stays (so the other component is being displayed below the navbar). My code does just that but I don't understand why. Could someone explain why when in my code, when I click for example on 'first', the search component is still displayed and below it my first component is rendered? Why won't only the first page being rendered? Thanks a lot!!
class App extends React.Component {
render () {
return(
<div>
<Switch>
<Route path='/first' component={BudgetSearch}/>
<Route path='/second' component={CheapestFareForDestination}/>
</Switch>
<Search />
</div>
)
}
}
export default App;
Search.jsx
class Search extends React.Component {
render () {
return (
<div>
<ul>
<li><Link to='/first'>first</Link></li>
<li><Link to='/second'>second</Link></li>
</ul>
</div>
)
}
}
export default Search;
Upvotes: 0
Views: 65
Reputation: 1010
It appears that your <Search />
component is not being wrapped by any <Route />
component. In essence, you're telling React that it should render <Search />
regardless of what route gets matched by the router. So whether your routes matches /first
, /second
or any other route, React will still render <Search />
because it "matches" all routes.
Upvotes: 2
Reputation: 5243
Change your App code to
class App extends React.Component {
render () {
return(
<div>
<Switch>
<Route path='/' component={Search}/>
<Route path='/first' component={BudgetSearch}/>
<Route path='/second' component={CheapestFareForDestination}/>
</Switch>
</div>
)
}
}
export default App;
This will render the search component when you are at the root of your application. But when you click on first
or second
it will navigate to the appropriate component and the Search component will not show any longer.
Previously, even though you were routing to the first
or second
components, you were always rendering the Search component inside your App component. This resulted in the Search component always showing up.
Upvotes: 2