Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display 404 when URL doesn't match any route and when the URL contains /#/ using ReactJS

This is my first time using ReactJS and is not my project however, I am trying to redirect any non-existent routes to a 404 page that I have made. My 404 page is currently displaying as intended when any URL that doesn't match a route is entered apart from when the URL contains /#/.

For example, this URL will redirect to my 404 page:

http://localhost:8080/non-existent-url

But this URL will only load my app's default route (homepage):

http://localhost:8080/#/non-existent-url

I don't know what the /#/ is for and it appears that the app will display pages with valid routes with or without it.

Stripped down routes file:

import React from "react";
import { Router, Route, IndexRoute, browserHistory, hashHistory, Redirect } from "react-router/es";
import willTransitionTo from "./routerTransition";
import App from "./App";
import DashboardContainer from "./components/Dashboard/DashboardContainer";
import DashboardAccountsOnly from "./components/Dashboard/DashboardAccountsOnly";
import NotFound from './components/NotFound';

const history = __HASH_HISTORY__ ? hashHistory : browserHistory;

class Auth extends React.Component {
    render() {return null; }
}

const routes = (
    <Route path="/" component={App} onEnter={willTransitionTo}>
        <IndexRoute component={DashboardContainer}/>
        <Route path="/auth/:data" component={Auth}/>
        <Route path="/dashboard" component={DashboardContainer}/>

        <Route path='*' exact={true} component={NotFound} />
    </Route>
);

export default class Routes extends React.Component {
    render() {
        return <Router history={history} routes={routes} />;
    }
}

404 (NotFound) component:

import React from 'react';
import {Link} from "react-router/es";
import Translate from "react-translate-component";

var image = require("assets/404.png");

const NotFound = () =>

    <div className="grid-block main-content wrap regular-padding">
        <div className="grid-content small-12" style={{marginTop:"200px"}}>
            <div style={{ textAlign:"center"}}>
                <img style={{marginBottom:"1.2rem"}} src={image} />
                <h3>404 page not found</h3>
                <p>This page does not exist.</p>
                <Link className="button" to={"/dashboard"}>
                    <Translate style={{color:"#fff"}} content="account.home" />
                </Link>
            </div>
        </div>
    </div>

export default NotFound;

How can I redirect users to my 404 page when a URL doesn't match any route and when the URL contains /#/?

like image 544
dom_ahdigital Avatar asked Jan 19 '18 16:01

dom_ahdigital


People also ask

What are two different ways to handle Page not found user experiences using react router?

An alternative way to handle 404 page not found in React router is to redirect the user to a different page when they try to go to a page that doesn't exist. Copied! In the example, instead of rendering a PageNotFound component, we redirect the user to / if they go to a route that doesn't exist. Copied!

How do I create a 404 page in react router?

Every Website needs a 404 page if the URL does not exist or the URL might have been changed. To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple react component called PagenotfoundComponent.

Which router hook will you use to get dynamic parameters from a URL?

The useParams Hook In addition, since the match object is passed from Route into the rendered component, you'll need to pass the dynamic routes along to components further down the DOM tree.


2 Answers

For react-router < 4.0

If you want to display an error page and not change the path

<Route path='*' exact={true} component={errorcomponent} />

If you want to display an error page and change the path

<Route path='/error' component={errorcomponent} />
 // use redirect to  change the Url
<Redirect from='*' to='/error' />

For react-router 4

Keep the path

<Switch>
    <Route exact path="/" component={component} />
    <Route component={errorcomponent} />
 </Switch>

change Url.

 <Switch>
    <Route path="/comp" component={component} />
   <Redirect to="/error" />
 </Switch>

the redirect tag has to be put whereever you place a route tag insde a switch.

like image 50
Sujit.Warrier Avatar answered Oct 20 '22 06:10

Sujit.Warrier


Based on what I'm seeing in your code, trying to switch between hash history and browser history just isn't going to work. The moment you hit '/#' in anything it's going to break and always hit your generic '/' route.

Hash URLs are an older way of handling things that shouldn't be an issue anymore. See this SO question and its accepted answer for more details.

Doing links like Twitter, Hash-Bang #! URL's

So yeah, unless you have some crazy reason to still support hashes in URLs, drop hash history and simply use browser history. Then your routes as defined in your provided code sample should work.

like image 43
MattD Avatar answered Oct 20 '22 07:10

MattD