0

I would like to catch 404 pages when user enter un Uri not defined in the app.

I have a Home route / . inside it I have children routes. Then I have other routes in top level ( same level as Home.

My problem is with the children routes /children1 /children2

When I type /strangeRoutereact loads the content of / then the 404 page.

That's because I'm not applying exact in Home route. And I should not add it because I should show Home content + Children1/Children2 content , not one or children routes.

The unique solution that I see is to store all routes then every page request (Using protected route ) check if the taped route correspond to an existing one, if not redirect it to 404 page.

Is there a simpler way to do it ?

import React from "react";
import {
  BrowserRouter as Router,
  Route, // for later
  Link
} from "react-router-dom";

const topics = [
  {
    name: "React Router",
    id: "react-router",
  },
  {
    name: "React.js",
    id: "reactjs",
  },
  {
    name: "Functional Programming",
    id: "functional-programming",
  }
];

function Home() {
  return (
    <div>
      <h1>Topics</h1>
      <ul>
        {topics.map(({ name, id }) => (
          <li key={id}>
            <Link to={`/${id}`}>{name}</Link>
          </li>
        ))}
      </ul>

      <hr />
      <Route exact path={`/react-router`} component={Topic} />
      <Route exact path={`/reactjs`} component={Topic} />
      <Route exact path={`/functional-programming`} component={Topic} />
    </div>
  );
}

function Topic() {
  return <div>TOPIC</div>;
}

function NotFound() {
  return <div>Page 404</div>;
}

class App extends React.Component {
  render() {
    return (
      <Router>
        <Route path="/" component={Home} />
        <Route component={NotFound} />
      </Router>
    );
  }
}

export default App;

I couldn't make a snipped here so here's a codesandbox example

jps
  • 20,041
  • 15
  • 75
  • 79
infodev
  • 4,673
  • 17
  • 65
  • 138

1 Answers1

0

Take a look at this Solution using redirects:

https://codesandbox.io/s/nested-routes-4-forked-scebd?file=/src/App.js

Master117
  • 660
  • 6
  • 21