How to use react-router BrowserRouter in a static index.html file
If your application is hosted on a static file server, you need to use a
<HashRouter>
instead of a<BrowserRouter>
.
FAQ.md#why-doesnt-my-application-render-after-refreshing
For a website like www.example.com/path/to/index.html
, you need to try a <HashRouter>
.
For a website like www.example.com
, <BrowserRouter>
might work. The server like Nginx needs an extra config for proper renders after refreshing non-root pages.
location / { try_files $uri /index.html;}
You don't have to use HashRouter
.
Just configure your static web server to serve index.html
for all the routes that you've defined. If you're using Nginx for example, see this example config file. If you're using Apache or Express, see this.
If you deploy your static site on DigitalOcean, you can specify all routes in the App Spec under Your App > Settings > App Spec
.
Just add a path
for each route to the file under static_sites > routes
.
Each route will then be forwarded to your / route where it will be handled by react router.
More info: https://docs.digitalocean.com/products/app-platform/concepts/http-route/