article

Showing posts with label ReactJS. Show all posts
Showing posts with label ReactJS. Show all posts

Sunday, May 28, 2023

React JS Python Flask Search Bar | Filter Search

React JS Python Flask Search Bar | Filter Search

Python Flask 

https://flask.palletsprojects.com/en/2.3.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-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, cross_origin #ModuleNotFoundError: No module named 'flask_cors' = pip install Flask-Cors
from models import db, Users

app = Flask(__name__)
   
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
#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'
   
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
   
CORS(app, supports_credentials=True)

db.init_app(app)
      
with app.app_context():
    db.create_all()

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

@app.route('/users', methods=['GET']) 
def users():
         
    total = Users.query.count()
     
    userdata = Users.query.order_by(Users.id.asc()).all()  
     
    return jsonify({
        'total': total,
        'results': [{
            'id': rs.id,
            'name': rs.name,
            'email': rs.email,
            'password': rs.password
        } for rs in userdata]
    })
   
if __name__ == "__main__":
    app.run(debug=True)
C:\flask_dev\flaskreact\models.py
#C:\flask_dev\flaskreact\models.py
from flask_sqlalchemy import SQLAlchemy
       
db = SQLAlchemy()
       
class Users(db.Model):
    __tablename__ = "tblusers"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(150), index=True, unique=True)
    email = db.Column(db.String(150), index=True, unique=True)
    password = db.Column(db.String(255), index=True, unique=True)
run (venv) C:\flask_dev\flaskreact>flask run
http://127.0.0.1:5000/users

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
//
import React, { useEffect, useState } from "react";
import "./App.css";

import SearchBar from "./Component/SearchBar";
//import allUsers from "./Data.json";

function App() {
	
	  const [allUsers, setAllcountry] = useState([]);
	
    useEffect(() => {
      const getusers = async () => {
        const getres = await fetch("http://127.0.0.1:5000/users");
        const setusers = await getres.json();
        //console.log(setusers.results);
        setAllcountry(await setusers.results);
      };
      getusers();
    }, []);
  
    return (
      <div className="App">
        <SearchBar placeholder="Enter a Name..." data={allUsers} />
      </div>
    );
}

export default App;
C:\react-js\myreactdev\src\Component\SearchBar.js
//C:\react-js\myreactdev\src\Component\SearchBar.js
import React, { useState } from "react";

function SearchBar({ placeholder, data }) {
  const [filteredData, setFilteredData] = useState([]);
  const [wordEntered, setWordEntered] = useState("");
	//console.log(data);
	
  const handleFilter = (event) => {
      const searchWord = event.target.value;
      setWordEntered(searchWord);
      const newFilter = data.filter((value) => {
        return value.name.toLowerCase().includes(searchWord.toLowerCase());
      });
      //console.log(searchWord);
      if (searchWord === "") {
        setFilteredData([]);
      } else {
        setFilteredData(newFilter);
      }
    };

  return (
        <div className="row d-flex justify-content-center ">
            <div className="col-md-6">
                <div className="form">
                <i className="fa fa-search"></i>
                <input
                  type="text"
                  placeholder={placeholder}
                  className="form-control form-input"
                  value={wordEntered}
                  onChange={handleFilter}
                />
                <span className="left-pan"><i className="fa fa-microphone"></i></span>
                </div>

				{filteredData.length !== 0 && (
					<div className="dataResult">
					  {filteredData.slice(0, 15).map((value, index) => {
						return (
						<div className="list border-bottom" key={index}>
							<div className="d-flex flex-column ml-3">
							  <span>{value.name}</span>
							</div>                   
						</div>
						);
					  })}
					</div>
				)}
				  
              </div>
        </div>
  );
}

export default SearchBar;
C:\react-js\myreactdev\src\Data.json
//C:\react-js\myreactdev\src\Data.json
[
	{
		"id":1,
		"name":"Cairocoders Ednalan",
		"email":"cairocoders@gmail.com"
	},
	{
		"id":2,
		"name":"clydey Ednalan",
		"email":"clydey@gmail.com"
	}
]
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"/>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
C:\react-js\myreactdev\src\App.css
//C:\react-js\myreactdev\src\App.css
body{
    background: #d1d5db;
}
.height{
    height: 100vh;
}
.form{
	margin-bottom:10px;margin-top:50px;
    position: relative;
}
.form .fa-search{
    position: absolute;
    top:20px;
    left: 20px;
    color: #9ca3af;
}
.form span{
    position: absolute;
    right: 17px;
    top: 13px;
    padding: 2px;
    border-left: 1px solid #d1d5db;

}
.left-pan{
    padding-left: 7px;
}
.left-pan i{
   padding-left: 10px;
}
.form-input{
    height: 55px;
    text-indent: 33px;
    border-radius: 10px;
}
.form-input:focus{
    box-shadow: none;
    border:none;
}

.list{
  background-color:#ffffff;	
  padding-top: 20px;padding-left:20px;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
}
.border-bottom{
  border-bottom: 2px solid #eee;
}
Run C:\react-j\myreactdev>npm start
http://localhost:3000/

React JS Laravel 10 Search Bar | Filter Search

React JS Laravel 10 Search Bar | Filter Search

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel10project>composer create-project laravel/laravel laravel10project

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Database Migration

C:\xampp\htdocs\laravel\my-app>php artisan migrate

php artisan tinker

User::factory()->count(100)->create()

Create Controller
C:\xampp\htdocs\laravel\laravel10project>php artisan make:controller UserController
app\Http\Controllers\UserController.php
//app\Http\Controllers\UserController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
       $users = User::all(); 
        
       // Return Json Response
       return response()->json([
            'results' => $users
       ],200);
    }
}
routes/api.php
//routes/api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('users', [UserController::class, 'index']);
Run C:\xampp\htdocs\laravel\laravel10project>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000/api/users

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
//
import React, { useEffect, useState } from "react";
import "./App.css";

import SearchBar from "./Component/SearchBar";
//import allUsers from "./Data.json";

function App() {
	
	  const [allUsers, setAllcountry] = useState([]);
	
    useEffect(() => {
      const getusers = async () => {
        const getres = await fetch("http://127.0.0.1:8000/api/users");
        const setusers = await getres.json();
        //console.log(setusers.results);
        setAllcountry(await setusers.results);
      };
      getusers();
    }, []);
  
    return (
      <div className="App">
        <SearchBar placeholder="Enter a Name..." data={allUsers} />
      </div>
    );
}

export default App;
C:\react-js\myreactdev\src\Component\SearchBar.js
//C:\react-js\myreactdev\src\Component\SearchBar.js
import React, { useState } from "react";

function SearchBar({ placeholder, data }) {
  const [filteredData, setFilteredData] = useState([]);
  const [wordEntered, setWordEntered] = useState("");
	//console.log(data);
	
  const handleFilter = (event) => {
      const searchWord = event.target.value;
      setWordEntered(searchWord);
      const newFilter = data.filter((value) => {
        return value.name.toLowerCase().includes(searchWord.toLowerCase());
      });
      //console.log(searchWord);
      if (searchWord === "") {
        setFilteredData([]);
      } else {
        setFilteredData(newFilter);
      }
    };

  return (
        <div className="row d-flex justify-content-center ">
            <div className="col-md-6">
                <div className="form">
                <i className="fa fa-search"></i>
                <input
                  type="text"
                  placeholder={placeholder}
                  className="form-control form-input"
                  value={wordEntered}
                  onChange={handleFilter}
                />
                <span className="left-pan"><i className="fa fa-microphone"></i></span>
                </div>

				{filteredData.length !== 0 && (
					<div className="dataResult">
					  {filteredData.slice(0, 15).map((value, index) => {
						return (
						<div className="list border-bottom" key={index}>
							<div className="d-flex flex-column ml-3">
							  <span>{value.name}</span>
							</div>                   
						</div>
						);
					  })}
					</div>
				)}
				  
              </div>
        </div>
  );
}

export default SearchBar;
C:\react-js\myreactdev\src\Data.json
//C:\react-js\myreactdev\src\Data.json
[
	{
		"id":1,
		"name":"Cairocoders Ednalan",
		"email":"cairocoders@gmail.com"
	},
	{
		"id":2,
		"name":"clydey Ednalan",
		"email":"clydey@gmail.com"
	}
]
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"/>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
C:\react-js\myreactdev\src\App.css
//C:\react-js\myreactdev\src\App.css
body{
    background: #d1d5db;
}
.height{
    height: 100vh;
}
.form{
	margin-bottom:10px;margin-top:50px;
    position: relative;
}
.form .fa-search{
    position: absolute;
    top:20px;
    left: 20px;
    color: #9ca3af;
}
.form span{
    position: absolute;
    right: 17px;
    top: 13px;
    padding: 2px;
    border-left: 1px solid #d1d5db;

}
.left-pan{
    padding-left: 7px;
}
.left-pan i{
   padding-left: 10px;
}
.form-input{
    height: 55px;
    text-indent: 33px;
    border-radius: 10px;
}
.form-input:focus{
    box-shadow: none;
    border:none;
}

.list{
  background-color:#ffffff;	
  padding-top: 20px;padding-left:20px;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
}
.border-bottom{
  border-bottom: 2px solid #eee;
}
Run C:\react-j\myreactdev>npm start
http://localhost:3000/

Thursday, May 25, 2023

React JS Laravel 10 AutoComplete Textbox | Filter Search

React JS Laravel 10 AutoComplete Textbox | Filter Search

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel10project>composer create-project laravel/laravel laravel10project

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create Model and Migration

C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Country -m

A new file named Country.php will be created in the app directory and database/migrations directory to generate the table in our database
app/Models/Country.php

//app/Models/Country.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    use HasFactory;

    protected $fillable = [
        'countryName'
    ];
}
database\migrations\create_countries_table.php
//database\migrations\create_countries_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->id();
            $table->string('countryName');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('countries');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravel10project>php artisan migrate
Migration table created successfully.

check database table
br/> Create Controller
C:\xampp\htdocs\laravel\laravel10project>php artisan make:controller AutoCompleteController

app\Http\Controllers\AutoCompleteController.php
//app\Http\Controllers\AutoCompleteController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Country;

class AutoCompleteController extends Controller
{
    public function index()
    {
       $countries = Country::all(); 
	   
       // Return Json Response
       return response()->json([
            'results' => $countries
       ],200);
    }
}
routes/api.php
//
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AutoCompleteController;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('autocomplete', [AutoCompleteController::class, 'index']); 
Run C:\xampp\htdocs\laravel\laravel10project>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000/autocomplete

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 Search() {
  const [allcountry, setAllcountry] = useState([]);
  const [filterresult, setFilterresult] = useState([]);
  const [serachcountry, setSearchcountry] = useState("");
 
  const handlesearch = (event) => {
    const search = event.target.value;
    console.log(search);
    setSearchcountry(search);
 
    if (search !== "") {
      const filterdata = allcountry.filter((item) => {
        return Object.values(item)
          .join("")
          .toLowerCase()
          .includes(search.toLowerCase());
      });
      setFilterresult(filterdata);
    } else {
      setFilterresult(allcountry);
    }
  };
 
  useEffect(() => {
    const getcountry = async () => {
      const getres = await fetch("http://127.0.0.1:8000/api/autocomplete");
      const setcounty = await getres.json();
      console.log(setcounty.results);
      setAllcountry(await setcounty.results);
    };
    getcountry();
  }, []);
 
  return (
      <div className="container">
        <div className="row"><h3>React JS Laravel 10 AutoComplete Textbox | Filter Search</h3>
          <div className="col-md-6 mb-3 mt-3">
            <input
              type="text"
              className="form-control"
              placeholder="Enter Keyword"
              onChange={(e) => {
                handlesearch(e);
              }}
            />
            <table className="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>Country ID </th>
                  <th>Country Name</th>
                </tr>
              </thead>
              <tbody>
                {serachcountry.length > 1
                  ? filterresult.map((filtercountry, index) => (
                      <tr key={index}>
                        <td> {filtercountry.id} </td>
                        <td> {filtercountry.countryName} </td>
                      </tr>
                    ))
                  : allcountry.map((getcon, index) => (
                      <tr key={index}>
                        <td> {getcon.id} </td>
                        <td> {getcon.countryName} </td>
                      </tr>
                    ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
  );
}
 
export default Search;
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/

Wednesday, May 17, 2023

React js Python Flask Mysql Show Product List with pagination Next Prev

React js Python Flask Mysql Show Product List with pagination Next Prev

Python Flask 

https://flask.palletsprojects.com/en/2.3.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-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, request, jsonify
from flask_cors import CORS, cross_origin #ModuleNotFoundError: No module named 'flask_cors' = pip install Flask-Cors
  
from models import db, Products
  
app = Flask(__name__)
  
app.config['SECRET_KEY'] = 'cairocoders-ednalan'
#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'
  
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_ECHO = True
  
CORS(app, supports_credentials=True)
  
db.init_app(app)
     
with app.app_context():
    db.create_all()
  
@app.route("/")
def hello_world():
    return "Hello, World!"
  
@app.route('/products/<int:page>/<int:per_page>', methods=['GET']) #http://127.0.0.1:5000/products/1/4
def products(page=1, per_page=4):
   
    nextpage = page + 1
    prevpage = page - 1
        
    total = Products.query.count()
    
    productdata = Products.query.order_by(Products.id.asc())  
    products = productdata.paginate(page=page, per_page=per_page)
    
    #print(products.next_num)
    #print(products.prev_num)
    
    nextnumber = products.next_num
    if nextnumber == None:
        next_page_url = ""
    else:
        next_page_url = f"http://127.0.0.1:5000/products/{nextpage}/{per_page}"
       
    prev_number = products.prev_num
    if prev_number == None:
        prev_page = ""
    else:
        prev_page = f"http://127.0.0.1:5000/products/{prevpage}/{per_page}"
        
    return jsonify({
        'total': total,
        'next_page_url': next_page_url,
        'prev_page_url': prev_page,
        'results': [{
            'id': rs.id,
            'name': rs.name,
            'image': rs.image,
            'description': rs.description
        } for rs in products.items]
    })
  
if __name__ == "__main__":
    app.run(debug=True)
C:\flask_dev\flaskreact\models.py
 
#C:\flask_dev\flaskreact\models.py
from flask_sqlalchemy import SQLAlchemy
      
db = SQLAlchemy()
      
class Products(db.Model):
    __tablename__ = "products"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(150), index=True, unique=True)
    image = db.Column(db.String(150), index=True, unique=True)
    description = db.Column(db.String(255), index=True, unique=True)
run (venv) C:\flask_dev\flaskreact>flask run
http://127.0.0.1:5000/products/1/4

Database Table

CREATE TABLE `products` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`description` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `products` (`id`, `name`, `image`, `description`) VALUES
(1, 'Asus Vivobook 14', '1.jpg', 'Asus Vivobook 14\" AMD Ryzen 3 3250 8gb/128gb M415DA-R3128 Slate [Grey]'),
(2, 'Acer Aspire 5 15.6', '2.jpg', 'Acer Aspire 5 15.6” laptop Ryzen 5-5500U 8GB RAM 512GB SSD - Silver'),
(3, 'Lenovo laptop t440', '3.jpg', 'Lenovo laptop t440 t450 t460 t470s i5 i7 5th gen 7th gen laptop built in camera for online class'),
(4, 'HP 3.0 2TB Flash Drive Metal', '4.jpg', 'HP 3.0 2TB Flash Drive Metal Waterproof High speed U Disk Flash Drive '),
(5, 'Desk Mat Laptop Mat Pad Gaming', '5.jpg', 'Desk Mat Laptop Mat Pad Gaming Large Mouse Pad Long Mousepad Leatherette Waterproof'),
(6, 'XIAOMI Original OTG metal pendrive 2TB', '6.jpg', 'XIAOMI Original OTG metal pendrive 2TB'),
(7, 'Monsy D103 Laptop Stand Aluminum Alloy', '7.jpg', 'Monsy D103 Laptop Stand Aluminum Alloy'),
(8, 'HD Webcam Web Camera', '8.jpg', 'HD Webcam Web Camera'),
(9, '300Mbps Wireless-N WiFi Repeater ', '9.jpg', '300Mbps Wireless-N WiFi Repeater '),
(10, 'Mumu 6033 Unisex 15.6 Inch Laptop', '10.jpg', 'Mumu 6033 Unisex 15.6 Inch Laptop Usb Backpack Anti Theft Men Bag Travel Male Leisure Bags'),
(11, 'Mini Computer Speakers Stereo USB Wired Powered for PC/Laptops/Smartphone', '11.jpg', 'Mini Computer Speakers Stereo USB Wired Powered for PC/Laptops/Smartphone');

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

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

Run
C:\react-js\myreactdev> npm start

https://github.com/axios/axios

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios
C:\react-js\myreactdev\src\App.js

//C:\react-js\myreactdev\src\App.js
import React, { useEffect, useState } from "react";
import axios from "axios";
// Component
import Navbar from "./Component/Navbar";
import ProductList from "./Component/ProductList";
 
function App() {
  const [products, setProducts] = useState([]);
  const [info, setInfo] = useState({});
  
  const url = "http://127.0.0.1:5000/products/1/4";
 
  const fetchProducts = (url) => {
    axios
      .get(url)
      .then((data) => {
        setProducts(data.data.results);
        //console.log(data.data.results);
        setInfo(data.data);
        //console.log(data.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };
   
  const handleNextPage = () => {
    fetchProducts(info.next_page_url);
    window.scrollTo(0, 0);
  };
  
  const handlePreviousPage = () => {
    fetchProducts(info.prev_page_url);
    window.scrollTo(0, 0);
  };
  
  useEffect(() => {
    fetchProducts(url);
  }, []);
 
 
  return (
    <>
      <Navbar brand="Cairocoders" />
 
      <div className="container py-5"><p><h2>React js Python Flask Mysql Show Product List with pagination Next Prev</h2></p>
        <nav>
  
          <ul className="pagination justify-content-center">
            {info.prev_page_url ? (
              <li className="page-item">
                <button className="page-link" onClick={handlePreviousPage}>
                  Previous
                </button>
              </li>
            ) : null}
            {info.next_page_url ? (
              <li className="page-item">
                <button className="page-link" onClick={handleNextPage}>
                  Next
                </button>
              </li>
            ) : null}
          </ul>
  
        </nav>
      </div>
       
      <ProductList products={products} />
       
      <div className="container pb-5">
        <nav>
          <ul className="pagination justify-content-center">
            {info.prev_page_url ? (
              <li className="page-item">
                <button className="page-link" onClick={handlePreviousPage}>
                  Previous
                </button>
              </li>
            ) : null}
            {info.next_page_url ? (
              <li className="page-item">
                <button className="page-link" onClick={handleNextPage}>
                  Next
                </button>
              </li>
            ) : null}
          </ul>
        </nav>
      </div>
	  
    </>
  );
}
 
export default App;
C:\react-js\myreactdev\src\Component\Navbar.js
//C:\react-js\myreactdev\src\Component\Navbar.js
import React from "react";
 
const Navbar = ({ brand }) => {
  return (
    <nav className="navbar navbar-dark bg-dark">
      <div className="container">
        <a className="navbar-brand text-uppercase" href="/">
          {brand}
        </a>
      </div>
    </nav>
  );
};
 
export default Navbar;
C:\react-js\myreactdev\src\Component\ProductList.js
//C:\react-js\myreactdev\src\Component\ProductList.js
import React from "react";
 
const ProductList = ({ products }) => {
  return (
    <div className="container">
      <div className="row">
        {products.map((item, index) => (
          <div key={index} className="col-lg-3 col-md-6 col-sm-12 mb-4">
            <div className="card" style={{ minWidth: "200px" }}>
                <img src={`http://127.0.0.1:5000/static/${item.image}`} alt="Product list" className="card-img-top" />
              <div className="card-body">
                <h5 className="card-title">{item.name}</h5>
                <hr />
                <p className="card-text">Description: {item.description}</p>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};
 
export default ProductList;
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/

Friday, May 12, 2023

React js Laravel 10 REST API Show Product List with pagination Next Prev

React js Laravel 10 REST API Show Product List with pagination Next Prev

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel10project>composer create-project laravel/laravel laravel10project

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create Model and Migration

C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Product -m

A new file named Product.php will be created in the app directory and database/migrations directory to generate the table in our database
app/Models/Product.php
//app/Models/Product.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 
        'image', 
        'description'
    ];
}
database\migrations\create_products_table.php
//database\migrations\create_products_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('image');
            $table->text('description');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravel10project>php artisan migrate
Migration table created successfully.
check database table
Create Controller and Request
C:\xampp\htdocs\laravel\laravel10project>php artisan make:controller ProductController -r

app\Http\Controllers\ProductController.php
//app\Http\Controllers\ProductController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Product;
use App\Http\Requests\ProductStoreRequest;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage; //php artisan storage:link = php artisan storage:link = http://127.0.0.1:8000/storage/1.jpg

class ProductController extends Controller
{
    public function index()
    {
       //$products = Product::all(); // All Product
      
       $products = Product::paginate(4);

       // Return Json Response
       return response()->json([
            'results' => $products
       ],200);
    }
  
    public function store(ProductStoreRequest $request)
    {
        try {
            $imageName = Str::random(32).".".$request->image->getClientOriginalExtension();
      
            // Create Product
            Product::create([
                'name' => $request->name,
                'image' => $imageName,
                'description' => $request->description
            ]);
      
            // Save Image in Storage folder
            Storage::disk('public')->put($imageName, file_get_contents($request->image));
      
            // Return Json Response
            return response()->json([
                'message' => "Product successfully created."
            ],200);
        } catch (\Exception $e) {
            // Return Json Response
            return response()->json([
                'message' => "Something went really wrong!"
            ],500);
        }
    }
}
Next, create a Request

C:\xampp\htdocs\laravel\laravel10project>php artisan make:request ProductStoreRequest
app\Http\Requests\ProductStoreRequest.php
//app\Http\Requests\ProductStoreRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProductStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        //return false;
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        if(request()->isMethod('post')) {
            return [
                'name' => 'required|string|max:258',
                'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                'description' => 'required|string'
            ];
        } else {
            return [
                'name' => 'required|string|max:258',
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                'description' => 'required|string'
            ];
        }
    }
 
    public function messages()
    {
        if(request()->isMethod('post')) {
            return [
                'name.required' => 'Name is required!',
                'image.required' => 'Image is required!',
                'description.required' => 'Descritpion is required!'
            ];
        } else {
            return [
                'name.required' => 'Name is required!',
                'description.required' => 'Descritpion is required!'
            ];   
        }
    }
}
Routes
All API requests will need the header Accept: application/json.
open routes/api.php and update the following code
routes\api.php
//routes\api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('products', [ProductController::class, 'index']); 
Route::post('products', [ProductController::class, 'store']); 
generate symbolic links C:\xampp\htdocs\laravel\laravel10project>php artisan storage:link

Run C:\xampp\htdocs\laravel\laravel10project>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

open postman new request

GET api/products Index All products return.
GET : http://127.0.0.1:8000/api/products

POST api/products Store Create a new product.
POST : http://127.0.0.1:8000/api/products
body
key value
name Iphone 13
image iphone.jpg = file
description product description

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

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

Run
C:\react-js\myreactdev> npm start

https://github.com/axios/axios

Installing the Axios Client
$ npm install axios

C:\reactdev\myreactdev>npm install axios
C:\react-js\myreactdev\src\App.js
//C:\react-js\myreactdev\src\App.js
import React, { useEffect, useState } from "react";
import axios from "axios";
// Component
import Navbar from "./Component/Navbar";
import ProductList from "./Component/ProductList";
 
function App() {
  const [products, setProducts] = useState([]);
  const [info, setInfo] = useState({});
  const url = "http://127.0.0.1:8000/api/products";
 
  const fetchProducts = (url) => {
    axios
      .get(url)
      .then((data) => {
        setProducts(data.data.results.data);
        //console.log(data.data.results.data);
        setInfo(data.data.results);
        //console.log(data.data.results.next_page_url);
      })
      .catch((error) => {
        console.log(error);
      });
  };
   
  const handleNextPage = () => {
    fetchProducts(info.next_page_url);
    window.scrollTo(0, 0);
  };
 
  const handlePreviousPage = () => {
    fetchProducts(info.prev_page_url);
    window.scrollTo(0, 0);
  };
   
  useEffect(() => {
    fetchProducts(url);
  }, []);
 
 
  return (
    <>
      <Navbar brand="Cairocoders" />
 
      <div className="container py-5"><p><h2>React js Laravel 10 REST API Show Product List with pagination Next Prev</h2></p>
        <nav>
 
          <ul className="pagination justify-content-center">
            {info.prev_page_url ? (
              <li className="page-item">
                <button className="page-link" onClick={handlePreviousPage}>
                  Previous
                </button>
              </li>
            ) : null}
            {info.next_page_url ? (
              <li className="page-item">
                <button className="page-link" onClick={handleNextPage}>
                  Next
                </button>
              </li>
            ) : null}
          </ul>
 
        </nav>
      </div>
       
      <ProductList products={products} />
 
      <div className="container pb-5">
        <nav>
          <ul className="pagination justify-content-center">
            {info.prev_page_url ? (
              <li className="page-item">
                <button className="page-link" onClick={handlePreviousPage}>
                  Previous
                </button>
              </li>
            ) : null}
            {info.next_page_url ? (
              <li className="page-item">
                <button className="page-link" onClick={handleNextPage}>
                  Next
                </button>
              </li>
            ) : null}
          </ul>
        </nav>
      </div>
       
    </>
  );
}
 
export default App;
C:\react-js\myreactdev\src\Component\Navbar.js
//C:\react-js\myreactdev\src\Component\Navbar.js
import React from "react";

const Navbar = ({ brand }) => {
  return (
    <nav className="navbar navbar-dark bg-dark">
      <div className="container">
        <a className="navbar-brand text-uppercase" href="/">
          {brand}
        </a>
      </div>
    </nav>
  );
};

export default Navbar;
C:\react-js\myreactdev\src\Component\ProductList.js
//C:\react-js\myreactdev\src\Component\ProductList.js
import React from "react";

const ProductList = ({ products }) => {
  return (
    <div className="container">
      <div className="row">
        {products.map((item, index) => (
          <div key={index} className="col-lg-3 col-md-6 col-sm-12 mb-4">
            <div className="card" style={{ minWidth: "200px" }}>
				<img src={`http://127.0.0.1:8000/storage/${item.image}`} alt="Product list" className="card-img-top" />
              <div className="card-body">
                <h5 className="card-title">{item.name}</h5>
                <hr />
                <p className="card-text">Description: {item.description}</p>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ProductList;
react-js\myreactdev\src\Index.css
//react-js\myreactdev\src\index.css
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
    "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background-color: #000000;
  overflow-x: hidden;
}

code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}
h2 {
	color:#fff;	
}		
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/

Friday, May 5, 2023

React Laravel 10 REST API Crud (Create, Read, Update and Delete) with Upload image

React Laravel 10 REST API Crud (Create, Read, Update and Delete) with Upload image

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel10project>composer create-project laravel/laravel laravel10project

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create Model and Migration

C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Product -m

A new file named Product.php will be created in the app directory and database/migrations directory to generate the table in our database
app/Models/Product.php

//app/Models/Product.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 
        'image', 
        'description'
    ];
}
database\migrations\create_products_table.php
//database\migrations\create_products_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('image');
            $table->text('description');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravel10project>php artisan migrate
Migration table created successfully.
check database table
Create Controller and Request
C:\xampp\htdocs\laravel\laravel10project>php artisan make:controller ProductController -r

app\Http\Controllers\ProductController.php
//app\Http\Controllers\ProductController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use App\Http\Requests\ProductStoreRequest;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage; //php artisan storage:link = php artisan storage:link = http://127.0.0.1:8000/storage/1.jpg

class ProductController extends Controller
{
    public function index()
    {
       // All Product
       $products = Product::all();
     
       // Return Json Response
       return response()->json([
          'products' => $products
       ],200);
    }
 
    public function store(ProductStoreRequest $request)
    {
        try {
            $imageName = Str::random(32).".".$request->image->getClientOriginalExtension();
     
            // Create Product
            Product::create([
                'name' => $request->name,
                'image' => $imageName,
                'description' => $request->description
            ]);
     
            // Save Image in Storage folder
            Storage::disk('public')->put($imageName, file_get_contents($request->image));
     
            // Return Json Response
            return response()->json([
                'message' => "Product successfully created."
            ],200);
        } catch (\Exception $e) {
            // Return Json Response
            return response()->json([
                'message' => "Something went really wrong!"
            ],500);
        }
    }
 
    public function show($id)
    {
       // Product Detail 
       $product = Product::find($id);
       if(!$product){
         return response()->json([
            'message'=>'Product Not Found.'
         ],404);
       }
     
       // Return Json Response
       return response()->json([
          'product' => $product
       ],200);
    }
 
    public function update(ProductStoreRequest $request, $id)
    {
        try {
            // Find product
            $product = Product::find($id);
            if(!$product){
              return response()->json([
                'message'=>'Product Not Found.'
              ],404);
            }
     
            //echo "request : $request->image";
            $product->name = $request->name;
            $product->description = $request->description;
     
            if($request->image) {

                // Public storage
                $storage = Storage::disk('public');
     
                // Old iamge delete
                if($storage->exists($product->image))
                    $storage->delete($product->image);
     
                // Image name
                $imageName = Str::random(32).".".$request->image->getClientOriginalExtension();
                $product->image = $imageName;
     
                // Image save in public folder
                $storage->put($imageName, file_get_contents($request->image));
            }
     
            // Update Product
            $product->save();
     
            // Return Json Response
            return response()->json([
                'message' => "Product successfully updated."
            ],200);
        } catch (\Exception $e) {
            // Return Json Response
            return response()->json([
                'message' => "Something went really wrong!"
            ],500);
        }
    }
 
    public function destroy($id)
    {
        // Detail 
        $product = Product::find($id);
        if(!$product){
          return response()->json([
             'message'=>'Product Not Found.'
          ],404);
        }
     
        // Public storage
        $storage = Storage::disk('public');
     
        // Iamge delete
        if($storage->exists($product->image))
            $storage->delete($product->image);
     
        // Delete Product
        $product->delete();
     
        // Return Json Response
        return response()->json([
            'message' => "Product successfully deleted."
        ],200);
    }
}
Next, create a Request

C:\xampp\htdocs\laravel\laravel10project>php artisan make:request ProductStoreRequest
app\Http\Requests\ProductStoreRequest.php
//app\Http\Requests\ProductStoreRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProductStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        //return false;
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        if(request()->isMethod('post')) {
            return [
                'name' => 'required|string|max:258',
                'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                'description' => 'required|string'
            ];
        } else {
            return [
                'name' => 'required|string|max:258',
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                'description' => 'required|string'
            ];
        }
    }
 
    public function messages()
    {
        if(request()->isMethod('post')) {
            return [
                'name.required' => 'Name is required!',
                'image.required' => 'Image is required!',
                'description.required' => 'Descritpion is required!'
            ];
        } else {
            return [
                'name.required' => 'Name is required!',
                'description.required' => 'Descritpion is required!'
            ];   
        }
    }
}
Routes
All API requests will need the header Accept: application/json.
open routes/api.php and update the following code
routes\api.php
//routes\api.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('products', [ProductController::class, 'index']); 
Route::get('products/{id}', [ProductController::class, 'show']); 
Route::post('products', [ProductController::class, 'store']); 
Route::put('productsupdate/{id}', [ProductController::class, 'update']);
Route::delete('productdelete/{id}', [ProductController::class, 'destroy']);
generate symbolic links C:\xampp\htdocs\laravel\laravel10project>php artisan storage:link

Run C:\xampp\htdocs\laravel\laravel10project>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

open postman new request

GET api/products Index All products return.
GET : http://127.0.0.1:8000/api/products

GET api/products/{id} Show Detail of a particular post by ID.
GET : http://127.0.0.1:8000/api/products/1

POST api/products Store Create a new product.
POST : http://127.0.0.1:8000/api/products
body
key value
name Iphone 13
image iphone.jpg = file
description product description

PUT api/products/{id} Update Update a particular product by ID.
POST : http://127.0.0.1:8000/api/products/1
body
key value
_method PUT
name Iphone 13 updated
image iphone.jpg = file
description product description updated

DELETE api/products/{id} Destroy Delete a particular product by ID.
DELETE : http://127.0.0.1:8000/api/products/1
React JS
https://create-react-app.dev/

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

Run
C:\react-js\myreactdev> npm start

https://github.com/axios/axios

Installing the Axios Client
$ npm install axios

Install React Router Dom
https://www.npmjs.com/package/react-router-dom
C:\react-js\myreactdev>npm i react-router-dom --save

C:\reactdev\myreactdev>npm install axios
C:\react-js\myreactdev\src\App.js
//C:\react-js\myreactdev\src\App.js
import React, {  } from "react";
import "./App.css";

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

import Header from './Component/Header';
import Home from './Component/Home';
import Addproduct from './Component/Addproduct';
import Productlist from './Component/Productlist';
import EditProduct from './Component/EditProduct';
import Footer from './Component/Footer';
function App() {
  return (
    <div className="App">
        <Router>
			<Header/>
            <Routes>
              <Route exact path="/" element={<Home/>}/>
              <Route exact path="/addproduct" element={<Addproduct/>}/>
              <Route exact path="/productlist" element={<Productlist/>}/> 
			  <Route path="editproduct/:id/edit" element={<EditProduct />} />
            </Routes>
			<Footer/> 
        </Router>
       
 </div>
  );
}

export default App;
C:\react-js\myreactdev\src\Component\Header.js
//C:\react-js\myreactdev\src\Component\Header.js
import React, {  } from "react";
import {NavLink} from 'react-router-dom';

function Header()
{
    return(
        <React.Fragment>
        <nav className="navbar navbar-expand-lg bg-primary" >
          <div className="container">
             <NavLink to="/" className="navbar-brand">Cairocoders</NavLink>
            <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span className="navbar-toggler-icon"></span>
              </button>
            <div className="collapse navbar-collapse" id="navbarSupportedContent">
            <ul className="navbar-nav me-auto mb-2 mb-lg-0">
            <li className="nav-item">
              <NavLink to="/" className="nav-link" aria-current="page">Home</NavLink>
            </li>
            <li className="nav-item">
              <NavLink to="/productlist" className="nav-link"> Product List</NavLink>
            </li> 
            <li className="nav-item">
              <NavLink to="/addproduct" className="nav-link">Add Product</NavLink>
            </li> 
          </ul>
    </div>
  </div>
</nav>
        </React.Fragment>
    );
}
export default Header;
C:\react-js\myreactdev\src\Component\Home.js
//C:\react-js\myreactdev\src\Component\Home.js
import React, {  } from "react";

function Home()
{
    return(
        <React.Fragment>
            <div className="container">
                <div className="row">
                    <div className="col-md-12">
                    <h1>React Laravel 10 REST API Crud (Create, Read, Update and Delete) with Upload image</h1>
                    </div>
                </div>
            </div>
        </React.Fragment>
    );
}
export default Home;
C:\react-js\myreactdev\src\Component\Footer.js
//C:\react-js\myreactdev\src\Component\Footer.js
import React, {  } from "react";

function Footer()
{
    return(
        <React.Fragment>
            <footer className="bg-primary fixed-bottom">
            <div className="container">
                <div className="row">
                    <div className="col-md-12 mt-3">
                        <p>Copyright @2023  Cairocoders</p>
                    </div>
                </div>
            </div>

            </footer>
            
        </React.Fragment>
    );
}
export default Footer;
C:\react-js\myreactdev\src\Component\Addproduct.js
//C:\react-js\myreactdev\src\Component\Addproduct.js
import React, { useState } from "react";

import axios from "axios";
import { useNavigate } from "react-router-dom";

function Addproduct()
{  
	const navigate = useNavigate();
	
    const[txtname, setName]= useState('');
    const[txtdescription, setdescription]= useState('');
    const[fileimage, setPhoto]= useState('');
    const[message, setMessage]= useState('');

    const uploadProduct= async()=>{
		console.log(fileimage)
        const formData= new FormData();
        formData.append('name', txtname);
        formData.append('description',txtdescription);
        formData.append('image', fileimage);
        const responce= await axios.post("http://127.0.0.1:8000/api/products", formData, {
            headers:{'Content-Type':"multipart/form-data"},
        } );

        if(responce)
        {
			console.log(responce)
            setMessage(responce.message); //"message": "Product successfully created."
            setTimeout(()=>{
                navigate('/productlist');
            }, 2000);
        }
    }

    const handleSubmit= async(e)=>{
      e.preventDefault();
      await uploadProduct();

   }
    return(
    <React.Fragment>
        <div className="container">
            <div className="row">
              <div className="col-md-8 mt-4">
                <h5 className="mb-4">Add Product </h5> 
                <p className="text-warning">{ message}</p>                              
                
                    <form onSubmit={ handleSubmit}>             
                    <div className="mb-3 row">
                    <label  className="col-sm-3">Product Title </label>
                    <div className="col-sm-9">
                    <input type="text" className="form-control" onChange={ (e)=>setName(e.target.value)}/>
                    </div>
                    </div>

                    <div className="mb-3 row">
                    <label  className="col-sm-3">Description </label>
                    <div className="col-sm-9">
                    <input type="text" className="form-control" onChange={(e)=>setdescription(e.target.value)}  />
                    </div>
                    </div>

                    <div className="mb-3 row">
                    <label  className="col-sm-3">Product Image</label>
                    <div className="col-sm-9">
                    <input type="file" className="form-control" onChange={(e)=>setPhoto(e.target.files[0])} />
                    </div>
                    </div>

                    <div className="mb-3 row">
                    <label className="col-sm-3"></label>
                    <div className="col-sm-9">
                    <button type="submit" className="btn btn-success">Submit</button>
                    </div>
                    </div>

                    </form>

             </div>
            </div>
        </div>
    </React.Fragment>
    );
}
export default Addproduct;
C:\react-js\myreactdev\src\Component\Productlist.js
//C:\react-js\myreactdev\src\Component\Productlist.js
import React, { useState, useEffect } from "react";

import { Link } from "react-router-dom";
import axios from "axios";

function Productlist()
{ 
	const[product, setProduct]= useState([]);
	
	useEffect( ()=>{
		const getProduct= ()=>{
			fetch("http://127.0.0.1:8000/api/products")
			.then(res=>{ return res.json()})
			.then(response=>{ 
				console.log(response.products)
				setProduct(response.products)
			})
			.catch(error=>{ console.log(error)});
		}
		getProduct();
	},[]);
 
  
    const deleteProduct = (id) => {
        axios.delete('http://127.0.0.1:8000/api/productdelete/'+id).then(function(response){
            console.log(response.data);
			alert("Successfully Deleted");
        });
    }
	
    return(
        <React.Fragment>
            <div className="container container_overflow">
                <div className="row">
                    <div className="col-12">
                        <h5 className="mb-4">Product List</h5> 
                        <p className="text-danger"> </p>                 
                                <table className="table table-bordered">
                                <thead>
                                <tr>
                                <th scope="col">Sr.No</th>
                                <th scope="col">Product Title</th>
                                <th scope="col">Product Description</th>
                                <th scope="col">Product Image</th>
                                <th scope="col" width="200">Action</th>
                                </tr>
                                </thead>
                                <tbody>
                                    {
                                        product.map((pdata, index)=>(
                                            <tr key={index}>
                                            <td>{index+1 } </td>
                                            <td>{pdata.name } </td>
                                            <td>{pdata.description } </td>
                                            <td><img src={`http://127.0.0.1:8000/storage/${pdata.image}`} alt="" height={50} width={90} /></td>
                                            <td>
												<Link to={`/editproduct/${pdata.id}/edit`} className="btn btn-success mx-2">Edit</Link>
												<button onClick={() => deleteProduct(pdata.id)} className="btn btn-danger">Delete</button>
                                            </td>
                                            </tr>
                                        ))
                                    }
                              
                                                               
                                </tbody>
                                </table>  
                    </div>
                </div>
            </div>
        </React.Fragment>
    );
}
export default Productlist;
C:\react-js\myreactdev\src\Component\EditProduct.js
//C:\react-js\myreactdev\src\Component\EditProduct.js
import React, { useState, useEffect } from "react";

import axios from "axios";
import { useParams, useNavigate } from "react-router-dom";

function EditProduct()
{
	const navigate = useNavigate();
	
    const {id}=   useParams();
	
    const[message, setMessage]= useState('');

	const [inputs, setInputs] = useState([]);
	const [fileimage, setPhoto]= useState('');
	
	const handleChange = (event) => {
        const name = event.target.name;
        const value = event.target.value;
        setInputs(values => ({...values, [name]: value}));
    }
	
    const uploadProduct= async()=>{
        const formData= new FormData();
        formData.append('_method', 'PUT');
        formData.append('name', inputs.name);
        formData.append('description',inputs.description);
        formData.append('image', fileimage);
        const response= await axios.post("http://127.0.0.1:8000/api/productsupdate/"+id, formData, {
            headers:{'Content-Type':"multipart/form-data"},
        } );
		setMessage(response.data.message); //"message": "Product successfully updated.."
		console.log(response)
        setTimeout(()=>{
            navigate('/productlist');
        }, 2000);
    }

    const handleSubmit= async(e)=>{
      e.preventDefault();
      await uploadProduct();

   }
   
    useEffect(() => {
        getproduct();
    }, []);
  
    function getproduct() {
        axios.get('http://127.0.0.1:8000/api/products/'+id).then(function(response) {
            console.log(response);
            setInputs(response.data.product);
        });
    }
	
    return(
    <React.Fragment>
        <div className="container">
            <div className="row">
              <div className="col-md-8 mt-4">
                <h5 className="mb-4">Edit Product </h5> 
                <p className="text-success"><b>{ message }</b></p>                              
                
                    <form onSubmit={ handleSubmit}>             
                    <div className="mb-3 row">
                    <label  className="col-sm-3">Product Title </label>
                    <div className="col-sm-9">
						<input type="text" value={inputs.name} className="form-control" name="name" onChange={ handleChange}/>
                    </div>
                    </div>

                    <div className="mb-3 row">
                    <label  className="col-sm-3">Description </label>
                    <div className="col-sm-9">
						<input type="text" value={inputs.description} className="form-control" name="description" onChange={ handleChange} />
                    </div>
                    </div>

                    <div className="mb-3 row">
                    <label  className="col-sm-3">Product Image</label>
                    <div className="col-sm-9">
						<img src={`http://127.0.0.1:8000/storage/${inputs.image}`} alt="" height={300} width={300} />
						<input type="file" className="form-control" onChange={(e)=>setPhoto(e.target.files[0])} />
                    </div>
                    </div>

                    <div className="mb-3 row">
                    <label className="col-sm-3"></label>
                    <div className="col-sm-9">
                    <button type="submit" className="btn btn-success">Submit</button>
                    </div>
                    </div>

                    </form>

             </div>
            </div>
        </div>
    </React.Fragment>
    );
}
export default EditProduct;
react-js\myreactdev\src\App.css
//react-js\myreactdev\src\App.css
body{
background:#eee;
}
.nav-link {
	color:#ffffff;
}	
.navbar-brand{
	color:#ffffff;
}	
.fixed-bottom{
	color:#ffffff;
}	
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/

Thursday, April 27, 2023

ReactJs Python Flask Dynamic Select Country State City | Axios Mysql

ReactJs Python Flask Dynamic Select Country State City | Axios Mysql

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, City
  
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')

class CitySchema(ma.Schema):
    class Meta:
        fields = ('id','name','stateid')

countries_schema = CountriesSchema(many=True)
state_schema = StateSchema(many=True)
city_schema = CitySchema(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)

@app.route('/city/<get_city>')
def city(get_city):
    city_data = City.query.filter_by(stateid=get_city).all()
    results = city_schema.dump(city_data)
    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)

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

Country State and City : https://github.com/cairocodes/cairocoders/blob/main/country-state-city.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

https://github.com/axios/axios

Installing the Axios Client
$ npm install axios

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

function App() {
  
  const [country, setCountry]= useState([]);
  const [countryid, setCountryid]= useState('0');
  const [stateid, setStateid]= useState('0');
  const [state, setState]= useState([]);
  const [city, setCity]= useState([]);

 
  useEffect(() => {
	  
    const fetchCountry = async () => {
        axios.get('http://127.0.0.1:5000/listall')
        .then(function (response) {
            //handle success
            //console.log(response)
            setCountry(response.data)
        })
        .catch(function (response) {
            //handle error
            console.log(response)
        });
    }
  
    fetchCountry()
  }, [])
 
  const handlecountry=(event)=>{
    const getcoutryid= event.target.value;
	alert(getcoutryid);
    setCountryid(getcoutryid);
    event.preventDefault();
  }  
  
  const handlestate=(event)=>{
    const stateid= event.target.value;
	alert(stateid);
    setStateid(stateid);
    event.preventDefault();
  }
 
  useEffect( ()=>{
 
    const getstate= async ()=>{	
        axios.get(`http://127.0.0.1:5000/state/${countryid }`)
        .then(function (response) {
            //handle success
            //console.log(response)
            setState(response.data)
        })
        .catch(function (response) {
            //handle error
            console.log(response)
        });
    }
    getstate();
 
  },[countryid]);
 
  useEffect( ()=>{
 
    const getcity= async ()=>{
        axios.get(`http://127.0.0.1:5000/city/${stateid }`)
        .then(function (response) {
            //handle success
            //console.log(response)
            setCity(response.data)
        })
        .catch(function (response) {
            //handle error
            console.log(response)
        });
    }
    getcity();
 
  },[stateid]);
	
  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 City | Axios Mysql</h5>

             <div className="row mb-3">
                 <div className="form-group col-md-12">
                 <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-12">
               <label className="mb-2">State</label>
               <select name="state" className="form-select" onChange={(e)=>handlestate(e)}>
                   <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-12">
               <label className="mb-2">City</label>
               <select name="city" className="form-select">
                   <option>--Select City--</option>                  
                   {
                     city.map( (st,index)=>(                    
                   <option key={index} value={st.id}>{ st.name}</option>
                     ))
                     }
                 </select>
               </div>
			   
               <div className="form-group col-md-12 mt-12">              
               <button type="submit" 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/

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