What Should You Know In React Js Before Creating A Simple CRUD Operations

Creating CRUD Operation from Scratch is an awesome things that every beginner wants to do.

In this blog We will provide some Code Snippets , methods and function by which you can simply perform CRUD in various Apps.

About The application :-

This app consists the List of Users details which you can add, modify, view or delete throughout the App.

The list of users is coming from JSON - Server and you can simple install JSON- server through

NPM(node package Manager)

To begin with crud you must be aware that CRUD is an abbreviation for Create, Read , Update and Delete.

first lets begin with Create 

1. CREATE /ADD users  -  Hooks method i.e., useHistory, useState 

                                            axios package 

                                            also array DE structuring


Code - 

import React,{useState} from 'react'

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

import axios from 'axios'


const Addusers = () =>{

    let history = useHistory();

    const [user,setUser] = useState({

        name:"",

        username:"",

        email:"",

        phone:"",

        website:""

    });

    const {name,username,email,phone,website} = user;

    const onInputChange = e =>{

        e.preventDefault();

        console.log(e.target.value)

        setUser({...user,[e.target.name]:e.target.value})

    };

    // const onClickChange = (event) =>{

    //     event.preventDefault();

    // }

    const onSubmitChange= async e =>{

        e.preventDefault();

        await axios.post("http://localhost:3001/users",user);

        history.push('/');

    }

    return(

        <>

        <div className="container">

        <form className="adduserform" onSubmit={e=>onSubmitChange(e)}>

            <h3>Add Users</h3>

            <label>Enter Your Name</label>

            <input type="text" name="name" value={name} onChange = {onInputChange}/>

            <label>Enter User Name</label>

            <input type="text" name="username" value={username} onChange = {onInputChange}/>

            <label>Enter E-mail Address</label>

            <input type="text" name="email" value={email} onChange = {onInputChange} />

            <label>Enter Phone Number</label>

            <input type="number" name="phone" value={phone} onChange = {onInputChange} />

            <label>Enter Your Business/Website</label>

            <input type="text"name="website" value={website} onChange = {onInputChange} />

            <button className="btn btn-primary" >Add User</button>

        </form>

        </div>

        </>

    )

}export default Addusers;

                                                                                                                                                                      

Edit User - Hooks method i.e., useState, useEffect ,useHistory , useParams
                                            axios package 
                                            also array DE structuring, spread Operator(...)


Code - import React,{useState,useEffect} from 'react'

import { useHistory,useParams } from 'react-router-dom';

import axios from 'axios'


const Edituser = () =>{

    let history = useHistory();

    const {id} = useParams()

    

    const [user,setUser] = useState({

        name:"",

        username:"",

        email:"",

        phone:"",

        website:""

    });

    const {name,username,email,phone,website} = user;

    const onInputChange = e =>{

        e.preventDefault();

        setUser({...user,[e.target.name]:e.target.value})

    };

    // const onClickChange = (event) =>{

    //     event.preventDefault();

    // }

    useEffect(()=>{

        loadUser()

    },[]);

    const onSubmitChange= async e =>{

        e.preventDefault();

        await axios.put(`http://localhost:3001/users/${id}`,user);

        history.push('/');

    }

    const loadUser = async () =>{

        const result = await axios.get(`http://localhost:3001/users/${id}`)

        setUser(result.data)

    }

    return(

        <>

        <div className="container">

        <form className="adduserform" onSubmit={e=>onSubmitChange(e)}>

            <h3>Edit User</h3>

            <label>Enter Your Name</label>

            <input type="text" name="name" value={name} onChange = {onInputChange}/>

            <label>Enter User Name</label>

            <input type="text" name="username" value={username} onChange = {onInputChange}/>

            <label>Enter E-mail Address</label>

            <input type="text" name="email" value={email} onChange = {onInputChange} />

            <label>Enter Phone Number</label>

            <input type="number" name="phone" value={phone} onChange = {onInputChange} />

            <label>Enter Your Business/Website</label>

            <input type="text"name="website" value={website} onChange = {onInputChange} />

            <button className="btn btn-warning" >Edit User</button>

        </form>

        </div>

        </>

    )

}

export default Edituser;

                                                                                                                                                                      

ViewUser - Hooks method i.e., useState, useEffect ,useParams
                                            axios package, Link for Routing Purpose 

code - import React, {useState,useEffect} from 'react'

import {Link,useParams} from 'react-router-dom'

import axios from 'axios';


const Viewuser = () => {

    const [user,setUser] = useState({

        name:"",

        username:"",

        email:"",

        phone:"",

        website:""

    });

    const {id} = useParams();

    useEffect(()=>{

        loadUser();

    },[])


    const loadUser= async () => {

        const res = await axios.get(`http://localhost:3001/users/${id}`)

        setUser(res.data)

    }

    return(

        <>  

            <div className="container">

                <Link className = "btn btn-primary m-3" to = "/">Back To Home</Link>

                <h1 className="display-4">Hello  {user.username}</h1>

                <h3>Your id is : {id} </h3>

                <hr />

                <ul className="list-group w-50">

                    <li className="list-group-item">

                        name :{user.name}

                    </li>

                    <li className="list-group-item">

                        name :{user.username}

                    </li>

                    <li className="list-group-item">

                        name :{user.email}

                    </li>

                    <li className="list-group-item">

                        name :{user.phone}

                    </li>

                    <li className="list-group-item">

                        name :{user.website}

                    </li>

                </ul>

            </div>

        </>

    )

}

export default Viewuser;

                                                                                                                                                                      

Delete users :- Delete user  operation can be perform on Home page as it is very simple you just have to calla function on an event  onDelete on button click which calls a function which perform delete task.
Also all the users shown on the home page so that a function named loadUsers also defined here
Array.map method is also gonna used so also raed that concept.


Code - import React, { useState, useEffect } from 'react'

import axios from 'axios'

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

import VisibilityIcon from '@material-ui/icons/Visibility';

import EditIcon from '@material-ui/icons/Edit';

import DeleteOutlineIcon from '@material-ui/icons/DeleteOutline';


const Home = () => {

    const [Users, setUsers] = useState([]);

    useEffect(() => {

        loadUsers();

    }, []);

    const loadUsers = async () => {

        const result = await axios.get('http://localhost:3001/users');

        setUsers(result.data.reverse());

    }

    const deleteUser = async (id) => {

        await axios.delete(`http://localhost:3001/users/${id}`)

        loadUsers();

    }

    return (

        <>

            <div className="container">

                <div className="py-4">

                    <div className="homepage">

                        <table class="table border shadow">

                            <thead >

                                <tr>

                                    <th scope="col">#</th>

                                    <th scope="col">Name</th>

                                    <th scope="col">User Name</th>

                                    <th scope="col">Email</th>

                                    <th>Action</th>

                                </tr>

                            </thead>

                            <tbody>

                                {Users.map((user, index) => (

                                    <tr>

                                        <th scope="row">{index + 1}</th>

                                        <td>{user.name}</td>

                                        <td>{user.username}</td>

                                        <td>{user.email}</td>

                                        <td>

                                            <Link class="btn btn-sm btn-outline-primary m-1" exact to={`/Viewuser/${user.id}`}><VisibilityIcon /></Link>

                                            <Link class="btn btn-sm btn-outline-primary m-1" exact to={`/Edituser/${user.id}`}><EditIcon /></Link>

                                            <Link class="btn btn-sm btn-outline-danger" onClick={() => {

                                                const confirmBox = window.confirm(

                                                    "Do you really want to delete this Data?"

                                                )

                                                if (confirmBox === true) {

                                                    deleteUser(user.id)

                                                }

                                            }}><DeleteOutlineIcon /></Link>

                                            {/* <Link class ="btn btn-sm btn-outline-danger" onClick = {()=>deleteUser(user.id)}><DeleteOutlineIcon/></Link> */}

                                        </td>

                                    </tr>

                                ))}

                            </tbody>

                        </table>

                    </div>

                </div>

            </div>

        </>

    )

}

export default Home

                                                                                                                                                                      

Also for Styling and action based performance some dependencies you need to install

1. Material UI Icons and Core

2. Axios for calling an API

3. Bootstrap for Styling

4.Concurrently for running two servers at a time on localhost

5. JSON Server - for testing API 

6. React Router Dom for routing purpose.

7. A Navbar , Footer, contact page, Gallery page, And about us page is also there and you can just simply create in your own way of creativity.

Output Images 


Home page

View Page


                                                                    Edit Page





Comments

Popular posts from this blog

Function in Javascript

Bihar hospitals run out of space as Coronavirus strains Health Services