Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the asterisk route always rendered?

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>
);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading