React.js integration with Flask (backend)

In modern web development, it is common to use separate technologies for the frontend and backend. React.js, a popular JavaScript library for building user interfaces, is often used for frontend development, while Flask, a lightweight web framework, is frequently used for backend development. In this blog post, we will explore how to integrate React.js with Flask to create a full-stack web application.

Prerequisites

Before we begin, make sure that you have the following installed and set up on your development environment:

Step 1: Setting up the Backend

Start by creating a new Flask project and setting up a basic server. Here’s a simple example to get you started:

from flask import Flask, jsonify, render_template

app = Flask(__name__)

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

@app.route("/api/data")
def api_data():
    data = {
        "message": "Hello from the backend!"
    }
    return jsonify(data)

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

In this example, we define two routes: / for serving the React.js frontend and /api/data for fetching data from the backend.

Step 2: Creating the React.js Frontend

Next, let’s create the React.js frontend by following these steps:

  1. Create a new directory for your frontend code and navigate into it.
  2. Initialize a new React.js project by running npx create-react-app ..
  3. Replace the contents of src/App.js with the following code:
import React, { useEffect, useState } from "react";

function App() {
  const [message, setMessage] = useState("");

  useEffect(() => {
    fetchData();
  }, []);

  async function fetchData() {
    const response = await fetch("/api/data");
    const data = await response.json();
    setMessage(data.message);
  }

  return (
    <div>
      <h1>React.js Integration with Flask</h1>
      <p>{message}</p>
    </div>
  );
}

export default App;

In this code, we use the useEffect hook to fetch data from the backend API endpoint /api/data and display it on the page.

  1. Run npm run build to build the React.js frontend.

Step 3: Integrating React.js with Flask

To integrate the React.js frontend into Flask, follow these steps:

  1. Copy the contents of the build directory (generated by npm run build) into your Flask project’s static directory.
  2. Update the index route in your Flask app to serve the React.js frontend:
@app.route("/")
def index():
    return render_template("index.html")
  1. Run your Flask server and navigate to http://localhost:5000 to see your React.js frontend integrated with Flask.

Conclusion

By following these steps, you have successfully integrated React.js with Flask. You now have a full-stack web application running, with Flask serving as the backend API and React.js handling the frontend UI. You can extend this example by adding more API endpoints or implementing additional functionality in React.js to create a more robust application.

#reactjs #flask