-1

Today I work on an one page in ReactJS. But I want a 404 notFoundPage component show up if there is no result in the url. I have used:

<Switch>
   <Route path="#index" component={Index} />
   <Route path="#about" component={About} />
   <Route path="#projects" component={Projects} />
   <Route path="#contact" component={Contact} />
   <Route exact component={PageNotFound} />
</Switch> 

and:

<Switch>
   <Route path="#index" component={Index} />
   <Route path="#about" component={About} />
   <Route path="#projects" component={Projects} />
   <Route path="#contact" component={Contact} />
   <Redirect component={PageNotFound} />
</Switch> 

Could someone help me out? I would appreciate it!

Thanks in advance

Valdemar Vreeman
  • 177
  • 2
  • 16
  • 1
    Does this answer your question? [React-Router: No Not Found Route?](https://stackoverflow.com/questions/32128978/react-router-no-not-found-route) – Rafael Tavares Aug 29 '20 at 17:36

2 Answers2

1

You're almost there in your first example, it should work if you remove the exact keyword:

<Switch>
   <Route path="#index" component={Index} />
   <Route path="#about" component={About} />
   <Route path="#projects" component={Projects} />
   <Route path="#contact" component={Contact} />
   <Route component={PageNotFound} />
</Switch>
Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
0

Please try the following code

  <Router>
    <Switch>
      <Route path="/about" exact name="about" component={About} />
      <Route path="/projects" exact name="projects" component={Projects} />
      <Route path="/contact" exact name="contact" component={Contact} />
      <Route component={PageNotFound} />
    </Switch>
    <Link to="/about" className="nav-link">
      <p>About</p>
    </Link>
    <Link to="/projects" className="nav-link">
      <p>Projects</p>
    </Link>
    <Link to="/contact1" className="nav-link">
      <p>Contact</p>
    </Link>
  </Router>

This code works and I tested that. You have to remember one thing here that "index" route is missing so whenever you will try to run http://localhost:3000 then it will show "page not found" component. If you will add an index route then the above code will work as intended and show "not found" page for any unmatched URL.

Nitesh Malviya
  • 794
  • 1
  • 9
  • 17