In the code below, Page2 is always rendered whether I am on Home or Page1. Ideally, I want Page2 to render only when the URL is not "/" or "/pageone", kind of like a 404 page.
Why is this happening?
// Import stuff using this syntax specifically for CodePen
const { HashRouter, Route, Link } = ReactRouterDOM;
const Home = () => (
<div class="container">
<h1>Home</h1>
<Link to="/pageone">Page 1</Link>
<Link to="/pagetwo">Page 2</Link>
</div>
);
const PageOne = () => (
<div class="container">
<h1>Page 1</h1>
</div>
);
const PageTwo = () => (
<div class="container">
<h1>Page 2</h1>
</div>
);
const App = () => (
<HashRouter>
<Route exact path="/" component={Home} />
<Route path="/pageone" component={PageOne} />
<Route path="*" component={PageTwo} />
</HashRouter>
);
>Solution :
All routes alone inside a router will always be inclusively matched and rendered. In other words, any and all matches will be rendered. If you want to exclusively match and render routes then render them within the Switch component. The Switch "renders the first child <Route> or <Redirect> that matches the location." Because of this you’ll want to keep in mind that route path order and specificity (i.e. how specific the path is) matters and you’ll want to order the routes from more specific paths to less specific paths.
const { HashRouter, Switch, Route, Link } = 'react-router-dom';
const App = () => (
<HashRouter>
<Switch>
<Route path="/pageone" component={PageOne} />
<Route exact path="/" component={Home} />
<Route path="*" component={PageTwo} />
</Switch>
</HashRouter>
);