Skip to content Skip to sidebar Skip to footer

Serve Another(standalone) Page Or Static File In Website Built With React

I have a website built with react, which uses react-router. For some route I want to serve another page or static file, but since all request are forwarded to react router, its doe

Solution 1:

This should work:

constreload = () => window.location.reload();

<Router>
  // all your routes..
  ...

  // Your special routes..
  <Routepath="/sitemap.xml"onEnter={reload} /><Routepath="/something.html"onEnter={reload} /></Router>

So, I think this should be pretty clear what it does ;)

Update:

if this is an option you can simply put target="_blank" attribute in your <Link>

IMHO this is from the UX perspective even better, because if these routes are not part of your main application, the user can just switch the Tab after visiting that special pages.

Solution 2:

It's an unwanted behaviour of ServiceWorker.js use the comment below and change it in index.js of your React project (if you don't need a service worker) and it should work

import { unregister } from'./registerServiceWorker';
unregister();

https://github.com/facebookincubator/create-react-app/issues/2715

If you still need a service worker and you want to avoid it having this behavior, consider installing a custom service worker, there you can establish a whitelist of paths to be ignored. For more information you can check the next link.

https://medium.com/swlh/how-to-implement-custom-service-worker-in-create-react-app-without-eject-bfa2c5f4ae96

Solution 3:

If you need /terms to redirect to /terms.html, the code below worked for me with react-router 3.x.

constreload = () => window.location.reload();
<Router><Switch><Routeexactpath="/"component={Home} /><Routepath="/terms.html"render={reload} /><Routepath="/privacy.html"render={reload} /><Routepath="/terms"render={() =><Redirectto={{pathname: "/terms.html"
        }}
      />} 
    />
    <Routepath="/privacy"render={() =><Redirectto={{pathname: "/privacy.html"
        }}
      />} 
    />
  </Switch></Router>

Solution 4:

Use Switch combined with a NoMatch component, combined with webdeb's solution:

<Router><div><Switch><Routeexactpath="/"component={Home} /><Routeexactpath="/admin"component={Admin} /><Routecomponent={NoMatch} /><RouteonEnter={() => window.location.reload()} />
    </Switch></div></Router>

This will match routes, show 404 if no valid href exists, and show a file or something if it's a valid href.

Solution 5:

How about simply put your statics files like sitemap.xml inside React's public folder along side index.html.

I thinks this is the easiest way.

enter image description here

Post a Comment for "Serve Another(standalone) Page Or Static File In Website Built With React"