How to create Crud Operation using React JS ?
In this Tutorial I will explain you How to perform Crud operation in React JS using material UI and Rest API server called Mock JSON server. So first we understand
what is Crud Operation ?
CRUD Operation Stand for Create, Read, Update and Delete
with help of crud operation we can create the data in form and Read the data in application and update or edit the data in our web application and delete the data from form or web application.
Project Name : Crud Operation using React JS
Technology Stack : React JS, Material UI, Rest API, JSON Server
How to set up project structure in React JS :
Software Requirement : Node JS, Visual Studio Code editor.
Step 1: Go to Command Prompt and run following command:
npx create-react-app crud-app
cd crud-app
npm run start
Install Material UI :
npm install @mui/material @emotion/react @emotion/styled
Install React Router DOM
npm i react-router-dom
Install Axios API :
npm i axios
Install JSON Server for Mock API Resosnce
npm i json-server
Step 2: After successfully installed react project in system final folder structure look like this.
- AddUser.js
- AllUser.js
- EditUser.js
- Home.js
- Navbar.js
Create database folder and inside this db.json file creation.
Create one service folder for api creation.
Step4: Write functional component code in above component.
App.js:
import { BrowserRouter,Routes,Route } from 'react-router-dom'; import './App.css'; import AddUser from './components/AddUser'; import AllUser from './components/Alluser'; import EditUser from './components/EditUser'; import Home from './components/Home'; import NavBar from './components/NavBar'; function App() { return ( <> <BrowserRouter> <NavBar/> <Routes> <Route path="/" element={<Home/>}/> <Route path ="add" element={<AddUser/>}/> <Route path="all" element={<AllUser/>}/> <Route path="edit/:id" element={<EditUser/>}/> </Routes> </BrowserRouter> </> ); } export default App;
Navbar.js:
import { AppBar, Toolbar, Typography,styled } from '@mui/material';import { NavLink } from 'react-router-dom';import React from 'react';const Header = styled(AppBar)`background:#111111;`const Tabs = styled(NavLink)`font-size:20px;margin-right:20px;color:inherit;text-decoration:none;`const NavBar =()=>{return(<Header position='static'><Toolbar><Tabs to ="./">Crud Operation</Tabs><Tabs to ="/all">All User</Tabs><Tabs to = "/add">Add User</Tabs></Toolbar></Header>);}export default NavBar;
AddUser.js
import React from 'react' import { FormControl, FormGroup, Typography } from '@mui/material' import { InputLabel,Input,Button,styled } from '@mui/material'; import { useState } from 'react'; import {addUser} from '../service/api' import { useNavigate } from 'react-router-dom'; const Container=styled(FormGroup)` width:50%; margin:5% auto 0 auto; &>div{margin-top:20px} ` const initialValue= { name:'', username:'', email:'', phone:'' } const AddUser =()=> { const [user,setUser]=useState(initialValue); const navigate=useNavigate(); const onValueChange=(e)=> { setUser({...user,[e.target.name]:e.target.value}) console.log(user); } const addUserDetails=async()=> { await addUser(user); navigate('/all'); } return( <Container> <Typography variant="h4">Add User</Typography> <FormControl> <InputLabel>Name</InputLabel> <Input onChange={(e)=>onValueChange(e)} name="name"/> </FormControl> <FormControl> <InputLabel>Username</InputLabel> <Input onChange={(e)=>onValueChange(e)} name="username"/> </FormControl> <FormControl> <InputLabel>Email</InputLabel> <Input onChange={(e)=>onValueChange(e)} name="email"/> </FormControl> <FormControl> <InputLabel>Phone No:</InputLabel> <Input onChange={(e)=>onValueChange(e)} name="phone"/> </FormControl> <FormControl> <Button variant="contained" onClick={()=>addUserDetails()}> Submit </Button> </FormControl> </Container> ) } export default AddUser;
EditUser.js
import React, { useEffect } from 'react' import { FormControl, FormGroup, Typography } from '@mui/material' import { InputLabel,Input,Button,styled } from '@mui/material'; import { useState } from 'react'; import {getUser,editUser} from '../service/api' import { useNavigate,useParams } from 'react-router-dom'; const initialValue= { name:'', username:'', email:'', phone:'' } const Container=styled(FormGroup)` width:50%; margin:5% auto 0 auto; &>div{margin-top:20px} ` const EditUser =()=> { const [user,setUser]=useState(initialValue); const navigate=useNavigate(); const {id} = useParams(); useEffect(()=>{ getUserData(); },[]) const getUserData= async()=> { let resposnce=await getUser(id); setUser(resposnce.data); } const onValueChange=(e)=> { setUser({...user,[e.target.name]:e.target.value}) console.log(user); } const addUserDetails=async()=> { await editUser(user,id); navigate('/all'); } return( <Container> <Typography variant="h4">Edit User</Typography> <FormControl> <InputLabel>Name</InputLabel> <Input onChange={(e)=>onValueChange(e)} name="name" value={user.name}/> </FormControl> <FormControl> <InputLabel>Username</InputLabel> <Input onChange={(e)=>onValueChange(e)} name="username" value={user.username}/> </FormControl> <FormControl> <InputLabel>Email</InputLabel> <Input onChange={(e)=>onValueChange(e)} name="email" value={user.email}/> </FormControl> <FormControl> <InputLabel>Phone No:</InputLabel> <Input onChange={(e)=>onValueChange(e)} name="phone" value={user.phone}/> </FormControl> <FormControl> <Button variant="contained" onClick={()=>addUserDetails()}> Submit </Button> </FormControl> </Container> ) } export default EditUser;
AllUser.js
import { useEffect,useState } from 'react'; import {Table,TableHead,TableRow,TableCell, TableBody,styled,Button } from '@mui/material'; import React from 'react' import { getUsers,deleteUser } from '../service/api'; import {Link} from 'react-router-dom' const StyledTable=styled(Table)` width:90%; margin:50px auto 0 auto; ` const THead=styled(TableRow)` background:#000; &>th { color:#fff; font-size:20px; } ` const TBody=styled(TableRow)` &>td { font-size:20px; } ` const AllUser =()=> { const [users,setUsers] = useState([]); useEffect(()=>{ getUserDetails(); },[]) const getUserDetails = async()=> { let resposnce = await getUsers(); console.log(resposnce); setUsers(resposnce.data); } const deleteUserData= async(id)=> { await deleteUser(id); getUserDetails(); } return( <StyledTable> <TableHead> <THead> <TableCell>ID</TableCell> <TableCell>Name</TableCell> <TableCell>Username</TableCell> <TableCell>Email</TableCell> <TableCell>Phone</TableCell> <TableCell>Edit </TableCell> <TableCell>Delete</TableCell> </THead> </TableHead> <TableBody> { users.map(user=>( <TBody> <TableCell>{user.id}</TableCell> <TableCell>{user.name}</TableCell> <TableCell>{user.username}</TableCell> <TableCell>{user.email}</TableCell> <TableCell>{user.phone}</TableCell> <TableCell> <Button color="primary" variant="contained" component={Link} to ={`/edit/${user.id}`}>Edit</Button> </TableCell> <TableCell> <Button color="secondary" variant="contained" onClick={()=>deleteUserData(user.id)}>Delete</Button> </TableCell> </TBody> )) } </TableBody> </StyledTable> ) } export default AllUser;
Home.js
import React from 'react' const Home =()=> { return( <> <h1>Project Name: Crud Operation using React JS</h1> <h3>Description: Crud Operation stand for Create, Read, Update and Delete the data</h3> <h3>Technology Stack : React JS, Material UI,Rest API, JSON Server</h3> <h3>React JS : React Routing,Hooks useState, useEffect,useParams,useNavigate</h3> <h3>Material UI : FormControl, FormGroup, Typography, InputLabel,Input,Button,styled,Table,TableHead,TableRow,TableCell, TableBody,styled,Button, AppBar, Toolbar</h3> <h3>Rest API Method: Get,Post,Put,Delete</h3> <h3>JSON Server: Fake JSON Server</h3> <h3>Error Handling: Try,Catch</h3> <h3>Async and Await Function in Javascript</h3> </> ) } export default Home;
{
"users": [
{
"name": "React",
"username": "React",
"email": "react@gmail.com",
"phone": "1234567890",
"id": 2
}
]
}
Create service/api.js
import axios from 'axios'; const API_URL="http://localhost:3002/users"; export const addUser=async(data)=> { try{ return await axios.post(API_URL,data); } catch(error) { console.log("Error while loading",error.message); } } export const getUsers = async()=> { try { return await axios.get(API_URL); } catch(error) { console.log("Error while loading data",error.message); } } export const getUser = async(data)=> { try { return await axios.get(`${API_URL}/${data}`); } catch(error) { console.log("Error while API calling getUserID data",error.message); } } export const editUser = async(data,id)=> { try{ return await axios.put(`${API_URL}/${id}`,data); } catch(error) { console.log("Error while updating data",error.message); } } export const deleteUser = async(id) => { try{ return await axios.delete(`${API_URL}/${id}`); } catch(error) { console.log("Error while callin delete API",error.message); } }
Add Package.json
"json-server":"json-server --watch src/database/db.json --host 127.0.0.1 --port 3002",
After written above code in run following command for run the project for start json server run the following command.
npm run json-server
After successfully run this project output for crud Operation.
So In this tutorial you learnt how to create crud operation using React JS with Material UI and Mock JSON server. Happy Learning Happy Coding!
No comments:
Post a Comment