What About Coding
By himanshu123Reactjsreactreact jscrud in react

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)

Watch video

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

&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta charset="utf-8" /&gt;
    &lt;link rel="icon" href="%PUBLIC_URL%/favicon.ico" /&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt;
    &lt;meta name="theme-color" content="#000000" /&gt;
    
    &lt;!-- Bootstrap 5 CSS CDN --&gt;
    &lt;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"
    /&gt;
    
    &lt;meta name="description" content="Web site created using create-react-app" /&gt;
    &lt;link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /&gt;
    &lt;link rel="manifest" href="%PUBLIC_URL%/manifest.json" /&gt;
    &lt;title&gt;React App&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;
    &lt;div id="root"&gt;&lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;

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 = () =&gt; {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const history = useNavigate();

  const handleSubmit = (e) =&gt; {
    e.preventDefault();
    console.log("clicked");
    axios
      .post("https://62a59821b9b74f766a3c09a4.mockapi.io/crud-youtube", {
        name: name,
        email: email,
      })
      .then(() =&gt; {
        history("/read");
      });
  };

  return (
    &lt;&gt;
      &lt;div className="d-flex justify-content-between m-2"&gt;
        &lt;h2&gt;Create&lt;/h2&gt;
        &lt;Link to="/read"&gt;
          &lt;button className="btn btn-primary"&gt;Show Data&lt;/button&gt;
        &lt;/Link&gt;
      &lt;/div&gt;
      &lt;form&gt;
        &lt;div className="mb-3"&gt;
          &lt;label className="form-label"&gt;Name&lt;/label&gt;
          &lt;input
            type="text"
            className="form-control"
            onChange={(e) =&gt; setName(e.target.value)}
          /&gt;
        &lt;/div&gt;
        &lt;div className="mb-3"&gt;
          &lt;label className="form-label"&gt;Email address&lt;/label&gt;
          &lt;input
            type="email"
            className="form-control"
            aria-describedby="emailHelp"
            onChange={(e) =&gt; setEmail(e.target.value)}
          /&gt;
        &lt;/div&gt;
        &lt;button
          type="submit"
          className="btn btn-primary"
          onClick={handleSubmit}
        &gt;
          Submit
        &lt;/button&gt;
      &lt;/form&gt;
    &lt;/&gt;
  );
};

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 = () =&gt; {
  const [data, setData] = useState([]);
  const [tabledark, setTableDark] = useState("");

  function getData() {
    axios
      .get("https://62a59821b9b74f766a3c09a4.mockapi.io/crud-youtube")
      .then((res) =&gt; {
        setData(res.data);
      });
  }

  function handleDelete(id) {
    axios
      .delete(`https://62a59821b9b74f766a3c09a4.mockapi.io/crud-youtube/${id}`)
      .then(() =&gt; {
        getData();
      });
  }

  const setToLocalStorage = (id, name, email) =&gt; {
    localStorage.setItem("id", id);
    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
  };

  useEffect(() =&gt; {
    getData();
  }, []);

  return (
    &lt;&gt;
      &lt;div className="form-check form-switch"&gt;
        &lt;input
          className="form-check-input"
          type="checkbox"
          onClick={() =&gt; {
            if (tabledark === "table-dark") setTableDark("");
            else setTableDark("table-dark");
          }}
        /&gt;
      &lt;/div&gt;
      &lt;div className="d-flex justify-content-between m-2"&gt;
        &lt;h2&gt;Read Operation&lt;/h2&gt;
        &lt;Link to="/"&gt;
          &lt;button className="btn btn-secondary"&gt;Create&lt;/button&gt;
        &lt;/Link&gt;
      &lt;/div&gt;
      &lt;table className={`table ${tabledark}`}&gt;
        &lt;thead&gt;
          &lt;tr&gt;
            &lt;th scope="col"&gt;#&lt;/th&gt;
            &lt;th scope="col"&gt;Name&lt;/th&gt;
            &lt;th scope="col"&gt;Email&lt;/th&gt;
            &lt;th scope="col"&gt;&lt;/th&gt;
            &lt;th scope="col"&gt;&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
          {data.map((eachData) =&gt; {
            return (
              &lt;tr key={eachData.id}&gt;
                &lt;th scope="row"&gt;{eachData.id}&lt;/th&gt;
                &lt;td&gt;{eachData.name}&lt;/td&gt;
                &lt;td&gt;{eachData.email}&lt;/td&gt;
                &lt;td&gt;
                  &lt;Link to="/update"&gt;
                    &lt;button
                      className="btn-success"
                      onClick={() =&gt;
                        setToLocalStorage(
                          eachData.id,
                          eachData.name,
                          eachData.email
                        )
                      }
                    &gt;
                      Edit
                    &lt;/button&gt;
                  &lt;/Link&gt;
                &lt;/td&gt;
                &lt;td&gt;
                  &lt;button
                    className="btn-danger"
                    onClick={() =&gt; handleDelete(eachData.id)}
                  &gt;
                    Delete
                  &lt;/button&gt;
                &lt;/td&gt;
              &lt;/tr&gt;
            );
          })}
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/&gt;
  );
};

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 = () =&gt; {
  const [id, setId] = useState(0);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const navigate = useNavigate();

  useEffect(() =&gt; {
    setId(localStorage.getItem("id"));
    setName(localStorage.getItem("name"));
    setEmail(localStorage.getItem("email"));
  }, []);

  const handleUpdate = (e) =&gt; {
    e.preventDefault();
    console.log("Id...", id);
    axios
      .put(`https://62a59821b9b74f766a3c09a4.mockapi.io/crud-youtube/${id}`, {
        name: name,
        email: email,
      })
      .then(() =&gt; {
        navigate("/read");
      });
  };

  return (
    &lt;&gt;
      &lt;h2&gt;Update&lt;/h2&gt;
      &lt;form&gt;
        &lt;div className="mb-3"&gt;
          &lt;label className="form-label"&gt;Name&lt;/label&gt;
          &lt;input
            type="text"
            className="form-control"
            value={name}
            onChange={(e) =&gt; setName(e.target.value)}
          /&gt;
        &lt;/div&gt;
        &lt;div className="mb-3"&gt;
          &lt;label className="form-label"&gt;Email address&lt;/label&gt;
          &lt;input
            type="email"
            className="form-control"
            value={email}
            onChange={(e) =&gt; setEmail(e.target.value)}
          /&gt;
        &lt;/div&gt;
        &lt;button
          type="submit"
          className="btn btn-primary mx-2"
          onClick={handleUpdate}
        &gt;
          Update
        &lt;/button&gt;
        &lt;Link to="/read"&gt;
          &lt;button className="btn btn-secondary mx-2"&gt;Back&lt;/button&gt;
        &lt;/Link&gt;
      &lt;/form&gt;
    &lt;/&gt;
  );
};

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 (
    &lt;div className="container"&gt;
      &lt;BrowserRouter&gt;
        &lt;Routes&gt;
          &lt;Route exact path="/" element={&lt;Create /&gt;} /&gt;
          &lt;Route path="/read" element={&lt;Read /&gt;} /&gt;
          &lt;Route path="/update" element={&lt;Update /&gt;} /&gt;
        &lt;/Routes&gt;
      &lt;/BrowserRouter&gt;
    &lt;/div&gt;
  );
}

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.

Share

More recent posts

View all