ReactJS and Flask

People building React apps usually code their server-side parts in Node.js (https://nodejs.org/en/), because it is simpler to stick with a single language and use its ecosystem for all the tools that are used when working with an application.

However, serving React apps with Flask is not a problem at all. The HTML page can be rendered using Jinja2, and the transpiled JSX files serve as static files like you would do for JavaScript files. Moreover, as we have seen in the previous section, we can get the React distribution as JS files, and just add them into our Flask static directory alongside other files.

Our Flask app, let's name it dashboard, will start off with a simple structure like this:

  • setup.py
  • dashboard/
    • __init__.py
    • app.py
    • templates/
      • index.html
    • static/
      • runs.jsx

Also, the app.py file, a basic Flask application that serves the unique HTML file, will be like this:

    from flask import Flask, render_template, 

app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html')

if __name__ == '__main__':
app.run()

Thanks to Flask's convention on static assets, all the files contained inside the static/ directory is served under the /static URL.

The index.html template looks like the one described in the previous section, and can grow into something Flask-specific later on.

That is all we need to serve a ReactJS-based app from Flask. However, dropping ReactJS distributions into your Flask static repository is not the best way to maintain your project. We need something better to manage JS dependencies. Moreover, the JavaScript world has great tools to do it as we will see in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset