Building mvp react full stack apps by Viet Phan Ventures

This article aims at describing how to serve a react application created using create-react-app with a Flask backend server. In other words, I will explain how to use Flask as your backend and React as your frontend all served through Flask.

Key terms

create-react-app: This a tool (built by developers at Facebook) that gives you a massive head start when building React apps. It saves you from time-consuming setup and configuration. You run one command, and Create React App sets up the tools you need to start your React project.

Flask: This a micro web framework written in python.

This article is suitable for anyone with a basic understanding of Python/flask and React and wants to explore how to build a full-stack web app using python-flask and React.
You can find the full implementation and code used in this article on this GitHub repository.

Requirements

  • yarn
  • Virtualenv
  • Flask
  • create-react-app

Let’s get started:

Install requirements

  • Download node for your operating system. Installing node will install npm as well.
  • Since we are going to use yarn as our package manager, go to your terminal and install yarn using this command npm install -g yarn .
  • Use yarn to install the other required packages. Run this command on your terminal yarn global add create-react-app react-scripts .
  • Open your project directory in your favorite IDE.
  • Run create-react-app react-app to create your react application. You can give the react app any name of your choice, but for this article, we are going to use react-app.
  • Activate your virtual environment and Install Flask using pip install flask.

The initial project set up

.
├── README.md
├── README.md
└── flask-server/
   └──static/
   └──templates/
   └── main.py
└── react-app/
   └── node_modules/
   └── public/
   └── src/

The react-app folder is the react application we created above with create-react-app command, flask-server/static folder is the path to where we shall build our react application, flask-server/templates will contain our HTML file from the react app, and the main.py file will contain our flask application.

Create the Flask app

Open your main.py file and paste the code below.

from flask import (Flask, render_template)

app = Flask("__main__")

@app.route("/")
def my_index():
    return render_template("index.html", flask_token="Hello   world")

app.run(debug=True)

Unpack webpack

To unpack webpack, make sure you are in the react-app directory and run this command; npm run eject. What this does is that it gives us access to the config files. It unpacks webpack.config.js as well as paths.js , which we are going to use to configure our build process.

Change building path

After unpacking webpack, you will notice a new folder created under react-app called config. We can now go ahead and edit our paths.js file by changing where we are building to. This can be achieved by changing our appbuild entry to the actual path where we want our files to go. Replace the appbuild entry with this line of code below.

appBuild: resolveApp('../flask-server/static/react'),

As you recall above, we created the static folder under the flask-server folder to contain the react application build. You also notice that I have added the react folder to the app build path because I wouldn’t want to build directly into the static folder that is why I have chosen to put the files under a sub-heading of react. Hence, after a complete build of the react application, you will notice that all the files will be in the react folder that will be created.

Edit webpack file

Open webpack.config.js file, you will notice there is a lot of static\ . What we want to do is to get rid of all of them. You can do this manually or use your editor to search for all of them and delete them at once. The next thing we need to do is to tell webpack where to put our HTML files. Got to the HtmlWebpackPlugin and add a file name to your config, as shown below;

new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
filename: "../../templates/index.html", //added line
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),

Make React interact with Flask

Open index.html, which is found in this path\react-app\public\index.html . After the title tag, add a script tag shown below.

<script> window.token="{{flask_token}}"</script>

NB. The flask_token is passed in through our flask backend. It is then accessible anywhere in our react app under window.token .
Let’s go into our App.js file, which is found in this path \react-app\src\App.js and add the line of code below to call out our token.

<p>My Token = {window.token}</p>

Tell React where to put the links to our javascript and CSS

Go to package.json file and add a new variable called homepage as, shown below.

"homepage": "/static/react",

Let’s now run our build using this command npm run build. You will notice the new files that got populated in our \flask-server\static\ folder. Then\flask-server\templates\ will contain the index.html file.

Finally, Run the flask application.

Change your Command-line directory to flask-server and run python3 main.py . Go to`http://localhost:5000/` to make sure your application runs as expected. If you have been building your application following this tutorial, compare it with the image below.

serve react with flask

NB: There is a drawback of losing the hot reload offered by the built-in debug server of NPM; hence, every time you make changes to the react app, you need to build it again with npm run build command to see the changes in your app.

Learning tools

Reflection

As a Python developer, I got curious about how I could serve a react app created by create-react- app with a flask server. And with this curiosity, I was able to achieve this.
NB. This can also be done using Python, NPM, WebPack, and React. Check out this link for a detailed approach.

Learning Strategy

Since I have prior experience with Python/Flask and React, I relied so much on learning how to change the building path of the react application that is created by running create-react-app .

Conclusion

I hope you have learned something new from this article. Feel free to leave any comment or suggestion in the comment section below.

Image Citation: https://www.vphventures.com/building-mvp-with-flask-day-3-adding-bootstrap-4/

Time report

Estimated project set up time: 2 hours.