I'm a React developer who's new to Flask. I'd like to route in backend with Flask and build frontend with React. My first scaffold looks like this:
Folder structure:
react-flask-app
-api
-app.py
-public
-index.html
-src
-pages
-Home.js
-Page1.js
-components
-Navbar.js
-App.js
App.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('../public/index.html')
Navbar.js:
const Navbar = () => {
return (
<>
<a href='/'>Home</a>
<a href='/page1'>Page 1</a>
</>
)
};
Home.js:
import Navbar from '../components/Navbar';
const Home = () => {
return (
<>
<Navbar />
<div>Homepage</div>
</>
)
}
Page1.js
import Navbar from '../components/Navbar';
const Page1 = () => {
return (
<>
<Navbar />
<div>Page 1</div>
</>
)
}
When I run the React app, I can switch between http://localhost:3000/
and http://localhost:3000/page1
by clicking the Navbar buttons, but it does not display Page1, since I've not set routing yet.
My question is, I know Flask can be used for routing, how can I use Flask to route and link to each page in this case?
To tell react to proxy any requests to Flask, add a proxy
field to your package.json
, e.g
"proxy": "http://localhost:5000",
Then use ajax
, fetch
from within your components to access your API.
More Information can be found in Proxying in development