If you're reading this, there is a high probability that you've deployed your first React app that uses React Router or the HTML5 history API, and routes entered into the browser directly return a page not found error. In this guide, you'll gain understanding of what the cause of this problem is and how to solve it.
To replicate the problem, you'll build and deploy a simple React app with two pages. First, create your React development environment with Create React App by entering the following command in your terminal.
1npx create-react-app [YOUR_APP_NAME]
Next add react-router-dom as a dependency
1yarn add react-router-dom
Create a Routes.js file and add the following to create the home and about page routes.
1import React from 'react'
2import { Route,Switch, BrowserRouter as Router } from 'react-router-dom'
3import { Home, About } from './app.js';
4
5const Routes = () => {
6 return (
7 <Router>
8 <Switch>
9 <Route exact path='/' component={Home}/>
10 <Route exact path='/about' component={About}/>
11 <Switch/>
12 </Router>
13 );
14};
15
16export default Routes;
Now create the components for the Home and About pages using the code below.
1import React from 'react';
2
3const Home = () => {
4 return(
5 <p>Homepage</p>
6 );
7}
8
9const About = () => {
10 return(
11 <p>About</p>
12 );
13}
14
15export default {Home , About}
Don't forget to add the routes
component to your index.js
page
1import React from "react";
2import ReactDOM from "react-dom";
3import Routes from "./Routes";
4
5ReactDOM.render(
6 <React.StrictMode>
7 <Routes />
8 </React.StrictMode>,
9 document.getElementById("root")
10);
There are a lot of ways to deploy your React app. In this guide you'll use render.com. But before deployment, run your build script and push your production build to a GitHub repository. Next, visit render.com and create an account if you don't have one.
Follow these steps to deploy your app:
Visit the About page. It doesn't work because in production the server looks for the file /about
, which literally doesn't exist.
To fix this issue, the server needs to be configured such that requests to any route would be served the index.html
file in your production build. If you use express.js
it can be done as follows.
1app.use(express.static(path.join(__dirname, 'build')));
2
3app.get('/*', function(req,res) {
4 res.sendFile(path.join(__dirname, 'build', 'index.html'));
5});
In your case render.com has a simple solution for that. On the dashboard for your app, click the Redirects/Rewrites tab and add the following:
1# Source: /*
2# Destination: /index.html
3# Action: Rewrite
Now save the changes and deploy your app again just to be sure. Your routes should work perfectly now.
Voila! You're a React guru now. If you'd like to read more on routing for Create React App in production, visit the official documentation. Ping me on Twitter if you'd like to chat more at @DesmondNyamador.