Ad

React: Router With Http Header Status

- 1 answer

I created my react app (client side rendering) as a single page app with react-router-dom. Catching the 404 pages is very simple using this:

import {Router} from 'react-router-dom';
import {Switch, Route, Redirect} from 'react-router-dom';
...

const Main = () => {
    return (
        <Router history={history}>
            <Switch>
                <Route exact path="/" component={Home}/>
                ...
                <Route path="*" status={404} component={PageNotFound}/>
            </Switch>
        </Router>
    )
};

export default Main;

This works. But when the PageNotFound component is rendered, the http header status is still 200, not 404 as expected.

Is there a way to set a 404 (or 301) page header when using client side rendering?

Ad

Answer

You should handle this on your server but if you still want to be able to set the http status code on client side, there is an npm package for this. Here

From the docs,

import React from "react";

import StatusCode from "konnektid-react-status";
// render your component
const MyComponent = () => (
  <StatusCode code={404}>
    Sorry, page was not found
  </StatusCode>
)
Ad
source: stackoverflow.com
Ad