Using Python Flask and React

If you want to use Flask and React together, here are the steps to follow.

First, create your react project in a folder.

mkdir python-react
cd python-react
npx create-react-app .

After your React project is installed, create a folder named api and install flask.

mkdir api
cd api
pip install flask

After installing Flask, open your package.json file in the python-react folder and add the following command under scripts

{
    ...
    scripts: {
        ...
        "start-flask": "cd api && export FLASK_APP=main.py && export FLASK_ENV=development && flask run",
    }
}

and add the proxy code at the bottom or somewhere appropriate

{
    ...
    "proxy": "http://127.0.0.1:5000"
}

We have installed flask in the api, let's create a main.py file and define a simple route in it.

cd api
touch main.py

Let's write the following codes in main.py

from flask import Flask
from time import time

app = Flask(__name__)

@app.route('/api/time')
def time():
    return {
        "time": time()
    }

now you can start react and flask like this

yarn start && yarn start-flask

In react, you can send a request to /api/time to show the returned response appropriately.

import {useState, useEffect} from 'react'

function App() {

  const [time, setTime] = useState(0)

  useEffect(() => {
    fetch('/api/time').then(res => res.json()).then(data => {
      setTime(data.time)
    })
  }, [])

  return (
    <div>
      Value from flask = {time}
    </div>
  );
}

export default App;
Comments

There are no comments, make the firs comment