Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrate React app into Flask app

Tags:

reactjs

flask

I have an existing Flask app with a static part (web pages) and a dynamic part (after login). What I need to do is rewrite the dynamic part as a React app which will use an existing API.

So far I've been building React apps that are completely decoupled and I don't know how to make the transition from Flask part to React part. Ideally, I don't want to just include React/React-DOM scripts in templates and write components, I'd like to write a single page app (using create-react-app) for the currently dynamic part of the Flask app.

Any ideas where the transition actually takes place? Maybe when @app.route(/dynamic-part) is fired, then write something other than render a template?

EDIT: because some users believe my question is not very clear, I'll try to be more precise in case somebody else stumbles upon this:

The issue I was asking about was how to switch from Flask handling it's part of the routes to React handling it's part of the routes without getting in each other's way. So, like the answer below suggests, I put the build output of the React app inside Flask and in Flask's routes pointed all the routes that are supposed to be handled by React app to the index.html of React's build output. That worked. Hopefully it's a bit more clear now. If not, I'll try again with more details.

like image 453
dnmh Avatar asked Mar 16 '17 00:03

dnmh


People also ask

Can we integrate React with flask?

Now, we provide the proxy in react package. json file because we need to access the flask URL in order to get the API from our react app. In general what proxy does is, when we request into the javascript web server which serves the react frontend will automatically be redirected to the proxy key.

Can we integrate React with Python?

This is because React uses a very different syntax and data structures than Python, which makes it difficult for Python developers to adapt to. In this article, we'll map out a road plan for getting started with React, as well as the core prerequisites for diving into React as a Python developer.


1 Answers

It looks like create-react-app has instructions re: building for relative paths. So you can develop the React app as usual.

Then, when you are ready, you 'npm run build,' which creates a build folder that has all the assets needed for your single page app (html, bundled javascript, css, etc). You can copy that entire folder into the directory with the rest of your templates. Then your @app.route(/dynamic-part) can point to ./app/templates/build/index.html.

like image 167
LShapz Avatar answered Sep 16 '22 23:09

LShapz