Display Search result in Model Box in MERN App

In this blog, we will learn about how to create a live search input field, which fetches the result as the user types in the search box. Live Search with React and NodeJS.

Search and Filter List Records

The back-end server uses Node.js + Express for REST APIs, front-end side is a React.js client with React Router, Axios & Bootstrap.

React, Node.js & MySQL CRUD example Short Description

  • REST APIs in Nodejs & interacts with MySQL Database using Sequelize ORM. React Client sends HTTP Requests and retrieves HTTP Responses using Axios, consume data on the components. React Router is used for navigating to pages.CRUD Operation Using React, Nodejs, Express & MySQL

Data base Design

--
-- Database: `node_react`
--

--
-- Table structure for table `employees`
--

CREATE TABLE `employees` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `phone` varchar(255) NOT NULL,
  `salary` varchar(255) DEFAULT NULL,
  `emp_image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employees`
--

INSERT INTO `employees` (`id`, `first_name`, `last_name`, `email`, `phone`, `salary`, `emp_image`) VALUES
(17, 'Benard', 'Litham', 'benard@gmail.com', '829299202', '80000', 'male.jpg'),
(18, 'Anu', 'Singh', 'bbsingh@gmail.com', '244244244', '50000', 'female.png'),
(19, 'Anthony ', 'Dsza', 'dyysengg@gmail.com', '922828222', '59999', 'male.jpg'),
(20, 'Baljeet', 'Singh', 'bls@yahoo.in', '948484444', '100000', 'male.jpg'),
(21, 'Anush', 'Sharma', 'ayush@gmail.com', '948485959', '100000', 'male.jpg'),
(22, 'Diney', 'Ahuja', 'diney@yahoo.in', '654484444', '50000', 'male.jpg'),
(23, 'Lavi', 'Singh', 'lavi@yahoo.in', '789393933', '60000', 'female.png'),
(24, 'Anana', 'Seth', 'anana@yahoo.in', '885757744', '100000', 'female.png'),
(25, 'Anaksha', 'Shah', 'anak@gmail.com', '893339393', '400000', 'female.png');

Node.js Back-end

We will follow MVC Pattern for making REST API in Nodejs .

CRUD in MERN

The src folder will have 3 folders :- controller , model & routes

First make MySQL Connection file inside config folder . We will call below config file in our src/models/employee.model.js file using this line of code . var dbConn  = require(‘../../config/db.config’); .

db.config.js

const mysql = require('mysql');
// create here mysql connection
const dbConn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'node_react'
});
dbConn.connect(function(error){
    if(error) throw error;
    console.log('Database Connected Successfully!!!');
})
module.exports = dbConn;

Now, We will make an index.js file which will include some important code of express js. You must install cors otherwise You will get a cors error in Reactjs form. ( npm install cors ) . We have already called cors in index.js file

index.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors'); // 

const app = express();

app.use(cors())
// create express app

// setup the server port
const port = process.env.PORT || 5000;

// parse request data content type application/x-www-form-rulencoded
app.use(bodyParser.urlencoded({extended: false}));

// parse request data content type application/json
app.use(bodyParser.json());

// define root route
app.get('/', (req, res)=>{
    res.send('Hello World');
});
// import employee routes
const employeeRoutes = require('./src/routes/employee.route');

// create employee routes
app.use('/api/v1/employee', employeeRoutes);

// listen to the port
app.listen(port, ()=>{
    console.log(`Express is running at port ${port}`);
});

Now We will make a controller file employee.controller.js inside the controllers’ folder. The Controller file will pass react form-data request to the model. The model will perform ADD, DELETE , UPDATE & DISPLAY Queries.

employee.controller.js ( src/controllers/employee.controller.js )

const EmployeeModel = require('../models/employee.model');

// get all employee list
exports.getEmployeeList = (req, res)=> {
    //console.log('here all employees list');
    EmployeeModel.getAllEmployees((err, employees) =>{
        console.log('We are here');
        if(err)
        res.send(err);
        console.log('Employees', employees);
        res.send(employees)
    })
}

// get employee by Name for earch by Name 
exports.getEmployeeByName = (req, res)=>{
    //console.log('get emp by id');
    EmployeeModel.getEmployeeByName(req.params.first_name, (err, employee)=>{
        if(err)
        res.send(err);
        console.log('single employee data',employee);
        res.send(employee);
    })
}

Now , We create a model file with named employee.model.js for CRUD Request .

employee.model.js ( src/controllers/employee.model.js )

var dbConn  = require('../../config/db.config');

var Employee = function(employee){
    this.first_name     =   employee.fname;
    this.last_name      =   employee.lname;
    this.email          =   employee.email;
    this.phone          =   employee.phone;
    this.salary         =   employee.salary;
    this.emp_image         =    employee.image;
}

// get all employees
Employee.getAllEmployees = (result) =>{
    dbConn.query('SELECT * FROM employees', (err, res)=>{
        if(err){
            console.log('Error while fetching employess', err);
            result(null,err);
        }else{
            console.log('Employees fetched successfully');
            result(null,res);
        }
    })
}

// get employee by Name for Search Data by name 
Employee.getEmployeeByName = (first_name, result)=>{
    dbConn.query('SELECT * FROM employees WHERE first_name LIKE ?', first_name+'%', (err, res)=>{
        if(err){
            console.log('Error while fetching employee by id', err);
            result(null, err);
        }else{
            result(null, res);
        }
    })
}
module.exports = Employee;

Now Last file is routing Which very important for any project . In this file We will make some routes for our React form request.

employee.route.js ( src/routes/employee.route.js )

const express = require('express');
const router = express.Router();

const employeeController = require('../controllers/employee.controller');

// get all employees
router.get('/', employeeController.getEmployeeList);

// get Detail by name 
router.get('/searchRecord/:first_name',employeeController.getEmployeeByName);

module.exports = router;

Our REST API is completed for NODEJS here now We will make React form.

ReactJS Front-end

We will use axios and fetch request in our React app . Read about more on Reactjs CRUD

To Install AXIOS You can use NPM or YARN npm install axios OR yarn add axios . We will also use Bootstrap for responsive Page . npm install bootstrap or yarn add bootstrap .

I am using Axios for data sending to Laravel so you can use fetch or Axios. To Install Axios write command npm install axios or yarn add axios. Read more about axios() and fetch()

Axios: Axios is a Javascript library used to make HTTP requests from node.js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6.

Fetch: The Fetch API provides a fetch() method defined on the window object. It also provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline (requests and responses). 

I will use Functional Component not Class component btw You can use Class component but hooks make our life easy in Function Component .

We will install more packages npm install react-router-dom ( for routing ) , and npm install react-bootstrap

  "axios": "^0.21.1",
    "bootstrap": "^5.0.1",
    "react": "^17.0.2",
    "react-bootstrap": "^1.6.0",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",

Now make a file named with EmployeeDetails.js . In this file we will have Code for DELETE , LIST and ADD .

EmployeeDetails.js

import 'bootstrap/dist/css/bootstrap.min.css';
import React, { useState, useEffect} from "react";
import axios from "axios";


function SearchEmployee()
{
  const [search,setSearch] =useState('');
  const [record,setRecord] = useState([]);

 
    // On Page load display all records 
    const loadEmployeeDetail = async () =>  
    {
      var response = fetch('http://localhost:5000/api/v1/employee')
         .then(function(response){
            return response.json();
          })
         .then(function(myJson) {
            setRecord(myJson);
          });
    }
    useEffect(() => {
      loadEmployeeDetail();
    }, []);

    // Search Records here 
    const searchRecords = () =>
    {
        axios.get(`http://localhost:5000/api/v1/employee/searchRecord/${search}`)
        .then(response => {
          setRecord(response.data);
        });
        
    }

    const loadRecordAgain = () =>
    {
      var response = fetch('http://localhost:5000/api/v1/employee')
      .then(function(response){
         return response.json();
       })
      .then(function(myJson) {
         setRecord(myJson);
       });
        
    }
    useEffect(() => {
      loadRecordAgain();
    }, []);


  return(
    <section>  
    <div class="container">  
    <h4 className="mb-3 text-center mt-4">Search Records in MERN</h4>
      <div class="row mt-3">
      <div class="col-sm-11">
        <div class="input-group mb-4 mt-3">
          <div class="form-outline">
           <input type="text" id="form1"    onKeyDown={loadRecordAgain} onKeyUp={searchRecords} onChange={(e)=>setSearch(e.target.value)} class="form-control" placeholder="Search Employee Here" style={{backgroundColor:"#ececec"}}/>
        </div>
        {/* <button type="button" onClick={searchRecords}  class="btn btn-success">
            <i class="fa fa-search" aria-hidden="true"></i>
        </button> */}
        </div>  
        <table class="table table-hover  table-striped table-bordered ml-4 ">
            <thead>
            <tr>
                <th>Name</th>
                <th>Surname</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Salary</th>
                <th>Image</th>
            </tr>
            </thead>
            <tbody>
    
            {record.map((name)=>
                <tr>
                <td>{name.first_name}</td>
                <td>{name.last_name}</td>
                <td>{name.email}</td>
                <td>{name.phone}</td>
                <td>{name.salary}</td>
                <td><img class="img-fluid" src={"/images/" + name.emp_image} style={{maxWidth:"40px"}}  alt=""/></td>
                </tr>
                )} 
            </tbody>
        </table>
      </div>
      </div>
    </div>
   </section>
  )
}

export default SearchEmployee;




Now Call SearchEmployee.js file in App.js.

App.js

import './App.css';
import SearchEmployee from './SearchEmployee';

function App() {
  return (
      <div className="App">
         <SearchEmployee />
      </div>
  );
}

export default App;

Finally, We have completed our Project Nodejs will run on http://localhost:5000/ and ReactJS will run on http://localhost:3000/ . You can change your PORT Setting.

Subscribe to My Programming YouTube Channel Before Downloading the code :

Download the Source Code : Search Records in MERN

Read Our More Articales on ReactJS and Nodejs

How to Load millions record in React

Building an Image Gallery with Laravel and React

How to search records in ReactJS

How To Create Charts In React With Database

Leave a Reply

Your email address will not be published. Required fields are marked *