1

I'm trying to merge an HTML/CSS admin template that I have bought online, into my CRA app.

The problem is that when I add the CSS of that template into my index.html inside the header section, and the CSS file does not exist, the server returns the home page.

I know this behavior is required for SPA, that server should return the home page for all routes, because routes are handled on the client-side, but in this case, I need to temporarily disable this feature and ask the server to return 404 if it does not find the resource.

How can I do it in create-react-app?

kelsny
  • 23,009
  • 3
  • 19
  • 48
tayebe pourmand
  • 185
  • 1
  • 5
  • What do you mean by return `404`? Are you referring to the response status code? If so, then it is not possible unless you are using your app along with a custom server. You cannot modify response status code/headers from the client code. If you just want to show a page showing that the resource doesn't exist then refer the [react-router documentation/examples](https://reactrouter.com/web/example/no-match). – brc-dd Jul 27 '21 at 11:51
  • Related: https://stackoverflow.com/questions/58233324/how-to-add-http-headers-in-react-js-apps-response – Jesse Nickles Aug 31 '22 at 10:31

1 Answers1

0

Create a 404 component. something like this:

import React from 'react';

const 404NotFound = () => {
  return <h1>404 Error</h1>;
}

export default 404NotFound;

Import the file inside your react routes configuration file something like this.

import 404NotFound from './404NotFound';

Include in your switch something like this after all the routes:

<Switch>
    ... other routes
    <Route component={404NotFound} />
</Switch>
KushalSeth
  • 3,265
  • 1
  • 26
  • 29
  • 1
    Note that this solution doesn't send any HTTP headers, it's only for displaying a "404 not found" type of template to users. – Jesse Nickles Aug 31 '22 at 09:15