Route 404 ошибка react

React Router is all about mapping URL paths to React components. However, sometimes you want React Router to render a component when none of the Routes match.

The most common use case for this is showing a 404 page. Regardless of if you want to show off your creative side or not, having a 404 page in place is a small thing that will go a long way for the UX of your site. Luckily, this is pretty simple to do with React Router’s Routes component.

Routes is the powerhouse of React Router. Whenever the app’s location changes, any Routes component will look through all its children Route elements to find the best match to render.

<Routes>

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

<Route path="/settings" element={<Settings />} />

</Routes>

Unlike previous versions of React Router, the order of the children Routes doesn’t matter since Routes is intelligent – meaning an algorithm now determines which is the best Route to render. This makes rendering a 404 component pretty simple.

All you have to do is render a Route with a path of *, and React Router will make sure to only render the element if none of the other Routes match.

<Routes>

<Route path="*" element={<NotFound />} />

<Route path="/" element={<Home />} />

<Route path="/about" element={<About />} />

<Route path="/settings" element={<Settings />} />

</Routes>

With react-router 2.0.0 you can do:

<Route path="*" component={NoMatch} status={404}/>

EDIT:

What you would need to do, is to create a custom attribute on your route definition, like you can see above (status).

When you are about rendering you component on server side, check on this attribute and send a response with a the code of this attribute:

routes.js

import React from 'react';
import {IndexRoute, Route} from 'react-router';

import {
    App,
    Home,
    Post,
    NotFound,
} from 'containerComponents';

export default () => {
    return (
    <Route path="/" component={App}>

        <IndexRoute component={Home} />
        <Route path='post/' component={Post} />

        { /* Catch all route */ }
        <Route path="*" component={NotFound} status={404} />

    </Route>
  );
};

server.js:

import { match } from 'react-router';
import getRoutes from './routes';
....
app.use((req, res) => {
match({ history, routes: getRoutes(), location: req.originalUrl }, (error, 
        redirectLocation, renderProps) => {
        if (redirectLocation) {
          res.redirect(redirectLocation.pathname + redirectLocation.search);
        } else if (error) {
          console.error('ROUTER ERROR:', error);
          res.status(500);
        } else if (renderProps) {

            const is404 = renderProps.routes.find(r => r.status === 404) !== undefined;
        }
        if (is404) {
          res.status(404).send('Not found');
        } else {
            //Go on and render the freaking component...
        }
    });
});

Sorry about that… certainly my solution wasn’t working by itself, and I missed the proper piece of code where you actually check on this attribute and render accordingly.

As you can see, I just send the ‘Not found’ text to the client, however, it would be best if you catch the component to render from renderProps (NoMatch in this case) and render it.

Cheers

Cover image for 404 Page with React Router V6.4

A 404 page can be incredibly useful in improving user experience. It is displayed when a user tries to access a page that does not exist on a website. In this article, we will explore two ways to implement a 404 page using React Router V6 in our React application.

Check out this post on my blog too!


Method 1

Suppose we have this basic route architecture:

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/blog" element={<Blog/>} />
  <Route path="/contact" element={<Contact/>} />
</Routes>

Enter fullscreen mode

Exit fullscreen mode

If a user enters a path that matches one of the options mentioned above, the respective component will be displayed. To add the 404 page, we can create a new route that displays the 404 page component for all paths. This can be achieved by using an asterisk (*) in the path.

As a result all paths will show the 404 component except the custom routes we have defined.

<Routes>
  <Route path='*' element={<ErrorPage/>} />
  <Route path="/" element={<Home />} />
  <Route path="/blog" element={<Blog/>} />
  <Route path="/contact" element={<Contact/>} />
</Routes>

Enter fullscreen mode

Exit fullscreen mode

Method 2

React Router V6.4 introduces a new hook for error handling, useRouteError.

Note: This feature only works if using a data router.

Once you have a data router installed and running, you can utilize useRouteError to catch any errors that occur during page loading or rendering, including the error that occurs when a page is not found. This makes debugging and error handling much simpler.

Firstly, let’s create an error page:

import { useRouteError } from "react-router-dom";

export default function ErrorPage() {
  const error = useRouteError();
  return (
    <div>
      <p style={{color: "red", fontSize:"30px"}}>
        {error.status == "404" ? "404 Page Not Found" : ""}
      </p>
    </div>
  );
}

Enter fullscreen mode

Exit fullscreen mode

In order to display an appropriate message when a page is not found using the useRouteError hook, you can simply receive the error from the hook and check its status. If the status is 404, you can return the appropriate message. Similarly, any other errors can be validated using this method.

Now we can implement this in our app. Keep in mind that we are using the new data APIs introduced in React Router V6.4. We will use the createBrowserRouter and RouterProvider to create the routes.

import { createBrowserRouter, RouterProvider } from "react-router-dom";
import Home from "./Pages/Home";
import Blog from "./Pages/Blog";
import About from "./Pages/About";
import ErrorPage from "./Extras/ErrorPage";

const router = createBrowserRouter([
  {
    path: "/",
    element: <Home />,
  },
  {
    path: "/blog",
    element: <Blog />,
  },
  {
    path: "/about",
    element: <About />,
  },
]);

function App() {
  return <RouterProvider router={router} />;
}
export default App;

Enter fullscreen mode

Exit fullscreen mode

The architecture describe above works exactly like the usual Routes and Route approach. We can now add the error page using errorElement in the root route.

const router = createBrowserRouter([
  {
    path: "/",
    element: <Home />,
    errorElement: <ErrorPage />
  },
  {
    path: "/blog",
    element: <Blog />,
  },
  {
    path: "/about",
    element: <About />,
  },
]);

Enter fullscreen mode

Exit fullscreen mode

The final output will look like this:

Routing


Thanks for reading!

Check out my blog too!

In this post you’ll learn how to handle 404 routes in React Router and provide a fallback component for displaying an imfamous 404 Page Not Found error to the user.

In React and React Router, we’re in the land of SPA (Single Page Apps), so naturally there will be no “404” page — but a component instead. The component will need displaying if a route isn’t recognised.

Thankfully, this is nice and easy in React Router!

Inside the <Switch /> component from React Router, we can declare a final <Route /> at the bottom of the route declarations.

🎉 React Router’s <Switch> component will render the first matched component, making it the perfect tool for us!

This means if the routes above haven’t matched, the only possible solution is we’ve hit a route that doesn’t actually exist.

I’ve setup a Hello and NotFound component and added them inside our App:

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Hello from './Hello';
import NotFound from './NotFound';

const App = () => (
  <Router>
    <Switch>
      <Route exact path="/" component={Hello} />
      <Route component={NotFound} />
    </Switch>
  </Router>
);

render(<App />, document.getElementById('root'));

Were you expecting more? That’s it! You don’t need to worry about path or exact, we can simply specify the component to render.

🙌 By not using path the route will always match, and it will only match when no other matches above were found.

Let’s use React Router’s <Link to="/oops" /> component inside our Hello component to let the user click and route to /oops — a route that does not exist in our app:

import React from 'react';
import { Link } from 'react-router-dom';

const Hello = () => (
  <div>
    <p>Click to route to "/oops" which isn't a registered route:</p>
    <Link to="/oops">Let's go</Link>
  </div>
);

export default Hello;

And here’s the NotFound component, it’s just a regular functional component that uses React Router’s <Link to="/"> to head back to the home page, or anywhere else you’d like in your app:

import React from 'react';
import { Link } from 'react-router-dom';

const NotFound = () => (
  <div>
    <h1>404 - Not Found!</h1>
    <Link to="/">Go Home</Link>
  </div>
);

export default NotFound;

Check out the live Stackblitz example below and watch the URL change (feel free to change the URL to anything and it will 404 on you):

Summary

A nice and easy post for React Router and how to provide a fallback component for when a route is not found.

Angular Directives In-Depth eBook Cover

Free eBook

Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.

I hope you enjoyed the post, and if you’d love to learn more please check out the React courses we’re working on where you’ll learn everything you need to know to be extremely good and proficient at React and the surrounding ecosystem, hooks and beyond!

By using React Router’s <Switch /> and adding the NotFound component at the bottom of our <Route /> declarations we are able to ensure that the route only works when we hit an unregistered route.

Happy coding!

This article walks you through an end-to-end example of adding a custom 404 (also known as Not Found or No Match) route to a React application that uses React Router 6 (the latest version).

Overview

In React Router 6 and newer, you can use a Route component with path=”*” to create a 404 route, like this:

<BrowserRouter>
   <Routes>
       <Route path="/" element={<HomePage />} />
       <Route path="/contact" element={<ContactPage />} />

       {/* 404 rounte */}
       <Route path="*" element={<NotFoundPage />} />
   </Routes>
</BrowserRouter>

For more clarity, please see the example below.

The Complete Example

App Preview

The app we are going to build contains 2 real pages: HomePage and ContactPage. On HomePage, there are some links that let a user navigate to some other routes.

  • If the user clicks a link whose target route doesn’t exist, our 404 error page will show up.
  • If the user types the wrong address in the browser’s address bar, our 404 page will appear.

For more convenience, the 404 page also provides a link to help the user quickly go back to HomePage.

A demo is worth more than a thousand words:

The Code

Install React Router:

npm i react-router-dom

The full source code with explanations in App.js (we don’t care about other files):

// App.js
import React from "react";

// import things from react-router-dom
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <div style={{ padding: 30 }}>
        <Routes>
          {/* 404 rounte */}
          <Route path="*" element={<NotFoundPage />} />
          <Route path="/" element={<HomePage />} />
          <Route path="/contact" element={<ContactPage />} />
        </Routes>
      </div>
    </BrowserRouter>
  );
}

// HomePage
const HomePage = () => {
  return (
    <div>
      <h1>Home Page</h1>
      <hr />
      <p>
        {/* This rounte exists */}
        <Link to="/contact">Contact Page (this is a working route)</Link>
      </p>
      <p>
        {/* This rounte doesn't exist thus you will end up on the 404 page */}
        <Link to="/terms-of-service">
          Terms of Service (this route doesn't exist)
        </Link>
      </p>
      <p>
        {/* This rounte doesn't exist thus you will end up on the 404 page */}
        <Link to="/something-else">Kitty Puppy (this is a non-exist page)</Link>
      </p>
    </div>
  );
};

// Contact
const ContactPage = () => {
  return (
    <div>
      <h1>Contact Page</h1>
    </div>
  );
};

// A custom 404 page
const NotFoundPage = () => {
  return (
    <div>
      <h1 style={{ color: "red", fontSize: 100 }}>404</h1>
      <h3>Page Not Found</h3>
      <p>
        <Link to="/">Go Home</Link>
      </p>
    </div>
  );
};

export default App;

Here’s my package.json:

{
  "name": "kindacode-example",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-device-detect": "^2.2.2",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.6.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Conclusion

You’ve learned how to implement a 404 page with React Router v6. This knowledge can help boost the user experience of your React app. If you’d like to explore more new and fascinating stuff about modern React development, take a look at the following articles:

  • React Router: Passing Data (States) through Links
  • React Router: 3 Ways to Disable/Inactivate a Link
  • React Router: How to Highlight Active Link
  • React + TypeScript: Re-render a Component on Window Resize
  • React + TypeScript: Handling onScroll event
  • Best Open-Source HTTP Request Libraries for React

You can also check our React category page and React Native category page for the latest tutorials and examples.

Понравилась статья? Поделить с друзьями:
  • Roundcube smtp ошибка 250 ошибка авторизации
  • Roundcube ошибка соединения сбой подключения к серверу
  • Rockstar games social club ошибка аутентификации попробуйте снова
  • Roominfo 1 ошибка сети
  • Rouge company ошибка 1000018808