article

Thursday, April 27, 2023

ReactJs Python Flask Dynamic Select Country State Dropdown Select Box

ReactJs Python Flask Dynamic Select Country State Dropdown Select Box

Python Flask 

https://flask.palletsprojects.com/en/2.2.x/installation/
 
Create an environment
C:\flask_dev>py -3 -m venv venv

Activate the environment
C:\flask_dev>venv\Scripts\activate

Install Flask
venv C:\flask_dev>pip install Flask
C:\flask_dev\flaskreact\app.py

Install requirements

Flask-SQLAlchemy
Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application.
https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/

(venv) PS C:\flask_dev\flaskreact>pip install -U Flask-SQLAlchemy

Flask + marshmallow for beautiful APIs
https://pypi.org/project/flask-marshmallow/

(venv) PS C:\flask_dev\flaskreact>pip install flask-marshmallow

Flask-Cors
A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.
https://pypi.org/project/Flask-Cors/

(venv) PS C:\flask_dev\flaskreact>pip install -U flask-cors

C:\flask_dev\flaskreact\app.py
 
#C:\flask_dev\flaskreact\app.py
from flask import Flask, jsonify
from flask_cors import CORS #ModuleNotFoundError: No module named 'flask_cors' = pip install Flask-Cors
from flask_marshmallow import Marshmallow #ModuleNotFoundError: No module named 'flask_marshmallow' = pip install flask-marshmallow https://pypi.org/project/flask-marshmallow/
  
from models import db, Countries, State
  
app = Flask(__name__)
CORS(app, supports_credentials=True)
  
#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///flaskdb.db'
# Databse configuration mysql                             Username:password@hostname/databasename
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:''@localhost/flaskreact'
  
db.init_app(app)
    
with app.app_context():
    db.create_all()
  
ma=Marshmallow(app)
   
class CountriesSchema(ma.Schema):
    class Meta:
        fields = ('ID','countryName')

class StateSchema(ma.Schema):
    class Meta:
        fields = ('id','name','country_id')

countries_schema = CountriesSchema(many=True)
state_schema = StateSchema(many=True)

@app.route("/")
def hello_world():
    return "Hello, World!"
  
@app.route('/listall',methods =['GET'])
def listall():
    all_countries = Countries.query.all()
    results = countries_schema.dump(all_countries)
    return jsonify(results)

@app.route('/state/<get_state>')
def statebycountry(get_state):
    state = State.query.filter_by(country_id=get_state).all()
    results = state_schema.dump(state)
    return jsonify(results)
C:\flask_dev\flaskreact\models.py
 
#C:\flask_dev\flaskreact\models.py
from flask_sqlalchemy import SQLAlchemy
     
db = SQLAlchemy()
     
class Countries(db.Model):
    __tablename__ = "countries"
    ID = db.Column(db.Integer, primary_key=True)
    countryName = db.Column(db.String(120), index=True, unique=True)

class State(db.Model):
    __tablename__ = "state"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120), index=True, unique=True)
    country_id = db.Column(db.Integer)
run (venv) C:\flask_dev\flaskreact>flask run
http://127.0.0.1:5000/users/1/4

Country and State : https://github.com/cairocodes/cairocoders/blob/main/country_state.sql

React JS
https://create-react-app.dev/

Create Project
C:\react-js>npx create-react-app myreactdev

Run
C:\react-js\myreactdev> npm start
C:\react-js\myreactdev\src\App.js

//C:\react-js\myreactdev\src\App.js
import React, { useState, useEffect } from "react";
import "./App.css";

function App() {
  const [country, setCountry]= useState([]);
  const [countryid, setCountryid]= useState('0');
  const [state, setState]= useState([]);
 
  useEffect( ()=>{
   const getcountry= async ()=>{
     const req= await fetch("http://127.0.0.1:5000/listall");
     const getres= await req.json();
     console.log(getres);
     setCountry(await getres);
 
   }
   getcountry();
 
 
  },[]);
 
  const handlecountry=(event)=>{
    const getcoutryid= event.target.value;
	alert(getcoutryid);
    setCountryid(getcoutryid);
    event.preventDefault();
  }
 
  useEffect( ()=>{
 
    const getstate= async ()=>{
      const resstate= await fetch(`http://127.0.0.1:5000/state/${countryid }`);
      const getst= resstate.json();
      console.log(getst);
      setState(await getst);
 
    }
    getstate();
 
  },[countryid]);
 
    
  return (
    <div className="container">
     <div className="row">
       <div className="col-sm-12">
         <h5 className="mt-4 mb-4 fw-bold">ReactJs Python Flask Dynamic Select Country State Dropdown Select Box</h5>
            
             <div className="row mb-3">
                 <div className="form-group col-md-4">
                 <label className="mb-2">Country</label>
                 <select name="country" className="form-select" onChange={(e)=>handlecountry(e)}>
                   <option>--Select Country--</option>
                   {
                     country.map( (getcon)=>(
                   <option key={getcon.ID} value={getcon.ID }> { getcon.countryName}</option>
                     ))
                }
                  
                 </select>
               </div>
               <div className="form-group col-md-4">
               <label className="mb-2">State</label>
               <select name="state" className="form-select">
                   <option>--Select State--</option>
                   {
                     state.map( (st,index)=>(                    
                   <option key={index} value={st.id}>{ st.name}</option>
                     ))
                     }
                 </select>
               </div>
 
               <div className="form-group col-md-2 mt-4">              
               <button className="btn btn-success mt-2" >Submit</button>               
               </div>
            </div>
                
       </div>
     </div>
    </div>
  );
}
export default App;
react-js\myreactdev\public\index.html
//react-js\myreactdev\public\index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"/>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
Run C:\react-j\myreactdev>npm start
http://localhost:3000/

Related Post