How to Perform CRUD Operations in React

CRUD stands for Create, Read, Update, and Delete.

Create: Creating or adding records.
Read: Reading or retrieving data from DB
Update: Updating or editing existing record.
Deleting: Deleting the record from the webpage

React is a JavaScript libraries for frontend development.

Create React Application

To create your React application, use

npx create-react-app <Your app name> using terminal,

npx create-react-app front

Install Router Dom

npm install react-router-dom

Then import “BrowserRouter” in index.js inside src dir

src\index.js

import {BrowserRouter} from 'react-router-dom'

Now replace <React.StrictMode> tag with BrowserRouter

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Replace with

root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

Add bootstrap (css and js CDN) in public/index.html file

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" >

 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js"></script>

Now create navbar in app.js file

src\App.js

Import React-Router-Dom in app.js

import {Routes, Route, Link} from 'react-router-dom';

And Create Link

<li className="nav-item">
    <Link className="nav-link active" aria-current="page" to={"/"}>Home</Link>
</li>

Create Routes , path and pass element in app.js

      <div className='container'>
        <Routes>
          <Route path='/' element={<home/>}></Route>
        </Routes>
      </div>

Create a new component ex: Home component (src/pages/Home.js)

We will keep all new components inside pages dir, so first create ‘pages’ dir inside ‘src’

export default function Home(){
    return (
    <>
      Home page working...
    </>
 )
}

Now import home component in app.js and then check browser.

import Home from './pages/Home';

Now create AddEmployee component inside ‘pages’ directory

export default function AddEmployee(){
    return (
    <>
    Employee page working...
    </>
    )
}

Import ‘AddEmployee’ in app.js

import AddEmployee from './pages/AddEmployee';

And create new link for employee in app.js

 <li className="nav-item">
     <Link className="nav-link" to="/AddEmployee">Add Employee</Link>
 </li>

Then add employee route in app js file

        <Routes>
          <Route path='/' element={<Home/>}></Route>
          <Route path='/AddEmployee' element={<AddEmployee/>}></Route>
        </Routes>

Now check your browser

Install axios

Axios is a promise based HTTP client for the browser . Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations.

npm install axios

Then create one base file (which is used for backend URL) for axios in src dir ex: http.js

import { type } from '@testing-library/user-event/dist/type';
import axios from 'axios';
export default axios.create({
    baseURL:"http://localhost:8000/api",
    headers:{
        "Content-type":"application/json"
    }
})

Import http, useState and useEffect inside home.js

import http from "../http"

Import state in home js for getting user records and useEffect for api calling when component will load, ( on the component load it will call useEffect function), so we can call any api inside it.

import { useState,useEffect } from "react"
import http from "../http"
export default function Home(){
    const [users, setUsers] = useState([]);

    useEffect(()=>{
        fetchUsers();
    },[]);

   const  fetchUsers = ()=>{
    http.get('/users').then(res=>{
        setUsers(res.data);
    })
    }
    
    return (
    <>
    <table className="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Name</th>
      <th scope="col">Email</th>
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    {users.map((user,i)=>
    <tr key={user.id}>
    <th scope="row" >{++i}</th>
    <td>{user.name}</td>
    <td>{user.email}</td>
    <td>
        <button className="btn btn-info mx-2">View</button>
        <button className="btn btn-primary mx-2">Edit</button>
        <button className="btn btn-danger mx-2">Delete</button>
    </td>
  </tr>
    )
    }
    
  </tbody>
</table>
    </>
    )
}

Create Laravel application for backend API.

composer create-project --prefer-dist laravel/Laravel backend
cd backend

Create UserController for CRUD API

php artisan make:controller UserController –-resource

Now include user model and return all records using usercontroller index function

use App\Models\User;
 
public function index()
    {
        return response()->json(User::latest()->get());
    }

Insert some dummy data using databaseseeder.php (database\seeders\DatabaseSeeder.php)

   public function run()
    {
         \App\Models\User::factory(10)->create();
    }

Create database in phpMyAdmin and configure it in .env file

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

For migrate you DB run migration and seeder command as below

php artisan migrate:fresh –seed

Check your database

Create route in api.php (routes\api.php)

use App\http\controllers\UserController;

Route::resouce('user',UserController::class);

Now run application using “php artisan serve” command

Create add employee form in react

export default function AddEmployee() {
    return (
        <>
<div className="container mt-5">
    <h2>Add Employee</h2>
<form>

                <div className="form-group col-6">
                    <label >Name</label>
                    <input type="text" className="form-control" name="name" placeholder="Enter Name"/>
                      
                </div>

                <div className="form-group col-6 mt-3">
                    <label >Email</label>
                    <input type="email" className="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter email"/>
                      
                </div>

                <div className="form-group col-6 mt-3">
                    <label >Password</label>
                    <input type="password" className="form-control" name="password" placeholder="Password"/>
                </div>
               
                <button type="submit" className="btn btn-primary mt-3">Submit</button>
            </form>
</div>
            

        </>
    )
}

Import useState, useNavigate and http in addemployee.js and create function for get/submit for value

import { useState } from "react";
import { useNavigate } from 'react-router-dom';
import http from "../http";

export default function AddEmployee() {
    const navigate = useNavigate();
    const [employeeInput, setEmployeeInput] = useState({});
    const handleChange = (e) =>{
        const name = e.target.name;
        const value = e.target.value;
        setEmployeeInput(values => ({...values,[name]:value}))
    }

    const addEmployee = ()=> {
        //console.log(employeeInput);
       http.post('/users',employeeInput).then((response)=>{
        console.log(response);
        navigate('/');
       })
    }
    return (
        <>
<div className="container mt-5">
    <h2>Add Employee</h2>
<form>

                <div className="form-group col-6">
                    <label >Name</label>
                    <input type="text" className="form-control" name="name" placeholder="Enter Name" value={employeeInput.name || ''} onChange={handleChange}/>
                      
                </div>

                <div className="form-group col-6 mt-3">
                    <label >Email</label>
                    <input type="email" name="email" className="form-control" aria-describedby="emailHelp" placeholder="Enter email" value={employeeInput.email || ''} onChange={handleChange}/>
                      
                </div>

                <div className="form-group col-6 mt-3">
                    <label >Password</label>
                    <input type="password" className="form-control" name="password" placeholder="Password" value={employeeInput.password || ''} onChange={handleChange}/>
                </div>
               
                <button type="button" onClick={addEmployee} className="btn btn-primary mt-3">Submit</button>
            </form>
</div>
            

        </>
    )
}

Create editEmployee js file for update records

src\pages\EditEmployee.js

import { useEffect, useState } from "react";
import { useNavigate,useParams } from 'react-router-dom';
import http from "../http";

export default function EditEmployee() {
    const navigate = useNavigate();
    const [employeeInput, setEmployeeInput] = useState({});
    const {id} = useParams(); //for get record ID

    useEffect(()=>{
        fetchEmployee();
    },[]);

    const fetchEmployee = ()=>{
        http.get('/users/'+id+'/edit').then((response)=>{
            setEmployeeInput({
                name:response.data.name,
                email:response.data.email
            })
        })
    }//);
    const handleChange = (e) =>{
        const name = e.target.name;
        const value = e.target.value;
        setEmployeeInput(values => ({...values,[name]:value}))
    }

    const updateEmployee = ()=> {
        //console.log(employeeInput);
       http.put('/users/'+id,employeeInput).then((response)=>{
        console.log(response);
        navigate('/');
       })
    }
    return (
        <>
<div className="container mt-5">
    <h2>Update Employee</h2>
<form>

                <div className="form-group col-6">
                    <label >Name</label>
                    <input type="text" className="form-control" name="name" placeholder="Enter Name" value={employeeInput.name || ''} onChange={handleChange}/>
                      
                </div>

                <div className="form-group col-6 mt-3">
                    <label >Email</label>
                    <input type="email" name="email" className="form-control" aria-describedby="emailHelp" placeholder="Enter email" value={employeeInput.email || ''} onChange={handleChange}/>
                      
                </div>
               
                <button type="button" onClick={updateEmployee} className="btn btn-primary mt-3">Submit</button>
            </form>
</div>
            

        </>
    )
}

Now import and create route in app.js file

import EditEmployee from './pages/EditEmployee';
        <Routes>
          <Route path='/' element={<Home/>}></Route>
          <Route path='/AddEmployee' element={<AddEmployee/>}></Route>
          <Route pass='/EditEmployee/:id’ element={<editEmployee/>}></Route>
        </Routes>

Create Edit link (Button) inside home.js

import {Link} from 'react-router-dom';

<Link to={{ pathname:"/editemployee/"+user.id}}>
       <button className="btn btn-primary mx-2">Edit</button>
       </Link>

Add update script in usercontroller for edit backend API

app\Http\Controllers\UserController.php

public function update(Request $request, $id)
    {
        $user = User::whereId($id)->first();
        
        $user->update([
            'name'=>$request->name,
            'email'=> $request->email
        ]);
        return response()->json("Record updated successfully");
    }

Now click on edit button

Update the record

Create ViewEmployee.js file in pages folder for view perticular record

Create fetchEmployee function for api and call it using useEffect

import { useEffect, useState } from "react";
import { useNavigate,useParams } from 'react-router-dom';
import http from "../http";

export default function ViewEmployee() {
    const navigate = useNavigate();
    const [employeeInput, setEmployeeInput] = useState({});
    const {id} = useParams(); //for get record ID

    useEffect(()=>{
        fetchEmployee();
    },[]);

    const fetchEmployee = ()=>{
        http.get('/users/'+id+'/edit').then((response)=>{
            setEmployeeInput({
                name:response.data.name,
                email:response.data.email
            })
        })
    }//);
   

   
    return (
        <>

        <table class="table">
        <thead>
            <tr>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
            <td>{employeeInput.name}</td>
            <td>{employeeInput.email}</td>
            </tr>
        </tbody>
        </table>
            

        </>
    )
}

Inside home.js file create delete button and call deleteemployee function on click

<button className="btn btn-danger mx-2" onClick={() => deleteEmployee(user.id)} >Delete</button>
 const deleteEmployee = (id)=>{
        http.delete('/users/'+id).then(res=>{
            fetchUsers();
        })
        }

For backend write delete API in usercontroller

app\Http\Controllers\UserController.php

   public function destroy($id)
    {
        User::whereId($id)->first()->delete();
        return response()->json("Record delete successfully");
    }

Leave a Reply

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