article

Sunday, May 28, 2023

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/

Related Post