article

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/

Related Post