CRUD in react js | React beginner tutorial
In this article, you will learn how to apply basic CRUD operations in React JS.
What is CRUD
CRUD stands for:
- Create
- Read
- Update
- Delete
No application in the world can be built without using CRUD operations.
For example, when you upload a picture on Facebook, that is a Create operation. When you refresh your feed to check likes or comments, that is a Read operation. If you notice a typo in your caption and fix it, that is an Update operation. Finally, if you decide to remove the post altogether, that is a Delete operation.
About the application
We are going to build a simple application where users can:
- Enter their name and email (Create)
- View their name and email (Read)
- Edit and update their name and email (Update)
- Delete their entry (Delete)
Let's build now
Prerequisites
- Basics of HTML, CSS, and JavaScript
- Familiarity with ES6 features
- Basics of React JS (Functional Components, Props, State, React Router, useState, useEffect)
Tech Stack
- React JS
- Axios (NPM Package)
- Bootstrap 5
- MockAPI (as a dummy backend server)
Setup & Installation
Create a new React project:
Bash
npx create-react-app CrudProject
Install the required dependencies:
Bash
npm i axios react-router-dom
public/index.html
Add the Bootstrap 5 CSS CDN inside the <head> tag:
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" />
<!-- Bootstrap 5 CSS CDN -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor"
crossorigin="anonymous"
/>
<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>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
Create.js (CREATE Operation)
JavaScript
import axios from "axios";
import React, { useState } from "react";
import { useNavigate } from "react-router";
import { Link } from "react-router-dom";
const Create = () => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const history = useNavigate();
const handleSubmit = (e) => {
e.preventDefault();
console.log("clicked");
axios
.post("https://62a59821b9b74f766a3c09a4.mockapi.io/crud-youtube", {
name: name,
email: email,
})
.then(() => {
history("/read");
});
};
return (
<>
<div className="d-flex justify-content-between m-2">
<h2>Create</h2>
<Link to="/read">
<button className="btn btn-primary">Show Data</button>
</Link>
</div>
<form>
<div className="mb-3">
<label className="form-label">Name</label>
<input
type="text"
className="form-control"
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="mb-3">
<label className="form-label">Email address</label>
<input
type="email"
className="form-control"
aria-describedby="emailHelp"
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<button
type="submit"
className="btn btn-primary"
onClick={handleSubmit}
>
Submit
</button>
</form>
</>
);
};
export default Create;
Read.js (READ & DELETE Operations)
JavaScript
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
const Read = () => {
const [data, setData] = useState([]);
const [tabledark, setTableDark] = useState("");
function getData() {
axios
.get("https://62a59821b9b74f766a3c09a4.mockapi.io/crud-youtube")
.then((res) => {
setData(res.data);
});
}
function handleDelete(id) {
axios
.delete(`https://62a59821b9b74f766a3c09a4.mockapi.io/crud-youtube/${id}`)
.then(() => {
getData();
});
}
const setToLocalStorage = (id, name, email) => {
localStorage.setItem("id", id);
localStorage.setItem("name", name);
localStorage.setItem("email", email);
};
useEffect(() => {
getData();
}, []);
return (
<>
<div className="form-check form-switch">
<input
className="form-check-input"
type="checkbox"
onClick={() => {
if (tabledark === "table-dark") setTableDark("");
else setTableDark("table-dark");
}}
/>
</div>
<div className="d-flex justify-content-between m-2">
<h2>Read Operation</h2>
<Link to="/">
<button className="btn btn-secondary">Create</button>
</Link>
</div>
<table className={`table ${tabledark}`}>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{data.map((eachData) => {
return (
<tr key={eachData.id}>
<th scope="row">{eachData.id}</th>
<td>{eachData.name}</td>
<td>{eachData.email}</td>
<td>
<Link to="/update">
<button
className="btn-success"
onClick={() =>
setToLocalStorage(
eachData.id,
eachData.name,
eachData.email
)
}
>
Edit
</button>
</Link>
</td>
<td>
<button
className="btn-danger"
onClick={() => handleDelete(eachData.id)}
>
Delete
</button>
</td>
</tr>
);
})}
</tbody>
</table>
</>
);
};
export default Read;
Update.js (UPDATE Operation)
JavaScript
import axios from "axios";
import React, { useEffect, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
const Update = () => {
const [id, setId] = useState(0);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const navigate = useNavigate();
useEffect(() => {
setId(localStorage.getItem("id"));
setName(localStorage.getItem("name"));
setEmail(localStorage.getItem("email"));
}, []);
const handleUpdate = (e) => {
e.preventDefault();
console.log("Id...", id);
axios
.put(`https://62a59821b9b74f766a3c09a4.mockapi.io/crud-youtube/${id}`, {
name: name,
email: email,
})
.then(() => {
navigate("/read");
});
};
return (
<>
<h2>Update</h2>
<form>
<div className="mb-3">
<label className="form-label">Name</label>
<input
type="text"
className="form-control"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="mb-3">
<label className="form-label">Email address</label>
<input
type="email"
className="form-control"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<button
type="submit"
className="btn btn-primary mx-2"
onClick={handleUpdate}
>
Update
</button>
<Link to="/read">
<button className="btn btn-secondary mx-2">Back</button>
</Link>
</form>
</>
);
};
export default Update;
App.js
JavaScript
import "./App.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Create from "./Components/Create";
import Read from "./Components/Read";
import Update from "./Components/Update";
function App() {
return (
<div className="container">
<BrowserRouter>
<Routes>
<Route exact path="/" element={<Create />} />
<Route path="/read" element={<Read />} />
<Route path="/update" element={<Update />} />
</Routes>
</BrowserRouter>
</div>
);
}
export default App;
Conclusion
In this article, you learned how to implement CRUD operations in React JS and how the axios package helps perform HTTP requests with an external API.