Reputation: 1902
I have a simple app:
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import './css/hind.css';
import './css/splash.css';
import Feedback from './components/Feedback';
import NotFound from './components/NotFound';
render((
<BrowserRouter>
<div className="add-100 dark-background">
<Route path="/" exact={true} component={Feedback}/>
<Route path="*" component={NotFound}/>
</div>
</BrowserRouter>
), document.getElementById('app'));
And I would expect that at the url /
I would see the first component, and at any other url, I would see the second. The NotFound
part is displaying how I would expect it too, but at /
, I see the first component, then the second component displayed beneath it. NotFound
is definitely not in my Feedback
file. How do I use the router correctly so I only display the component I want it to?
Upvotes: 0
Views: 430
Reputation: 35286
path="*"
isn't actually supported in RRv4. Instead, a Route with no path property will always match. Combining the knowledge with the Switch
component, you'll get the desired outcome. Switch
will only render the first matching Route
, so the idea is that if none of your other Route
s match, then the last Route
in your Switch
component will render.
<Switch>
<Route path="/" exact={true} component={Feedback}/>
<Route component={NotFound}/>
</Switch>
Upvotes: 1
Reputation: 5293
Wrap your routes with <Switch />
.
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import './css/hind.css';
import './css/splash.css';
import Feedback from './components/Feedback';
import NotFound from './components/NotFound';
render((
<BrowserRouter>
<div className="add-100 dark-background">
<Switch>
<Route path="/" exact={true} component={Feedback}/>
<Route path="*" component={NotFound}/>
</Switch>
</div>
</BrowserRouter>
), document.getElementById('app'));
What does <Switch />
exactly do?
It renders the first child <Route>
or <Redirect>
that matches the location.
Upvotes: 2