Create in React.js CRUD Operations

Introduction

In my previous article, Read in React.js CRUD Operations. The 'Read' operation involves fetching, displaying, and managing data. The article introduces state management using functional components with hooks. A practical example demonstrates data fetching using Axios, and the article explores the useState and useEffect hooks. It then explains the use of the map() function to display fetched data. The article concludes by creating a table view for the data and integrating it into the React application.

  1. Read in React.js CRUD Operations
  2. MVC Architecture With Node.js CRUD Application [Node.js-Express-MongoDB]
  3. View in React.js within the MVC Architecture
  4. Impact of React in MERN Stack Development

I have attached a zip file containing the source code for the Node.js API and React.js in this article.

Introduction Create (C)

Certainly! CRUD stands for Create, Read, Update, and Delete, which are the basic operations that can be performed on data in a database or any data storage system. These operations are fundamental in the context of database management and are commonly used in software development. Let's go through each operation:

Purpose and Action of 'Create' Operation

Purpose: The Create operation is used to add new data records to the database.

Action: It involves inserting a new record or object into the database.

Example: In a student management system, the Create operation would be used to add a new student to the system by inserting a new row in the student table.

CREATE

Picture 1. Student management system Create operation.

My previous article (Read in React.js CRUD Operations) concludes by creating a table view for the data and integrating it into the React application. A little bit modified my code using CSS.

Student table

Picture 2. Added edit and delete button

Modifying Folder Structure and Creating Student Page

Let's begin by practically creating a student. First, I'm going to modify the folder structure.

Create a new folder named 'page' inside the 'src' folder. Within the 'page' folder, create a new file named 'student.jsx' for the student page.

Explorer

Picture 3. Inside the page folder, student.jsx

Sharing the student.jsx page

import React, { useState, useEffect } from "react";
import axios from "axios";
import DataTable from "../component/table";

export default function Student() {
  const [data, setData] = useState([]);

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

  const fetchStudentData = async () => {
    const res = await axios.get("http://localhost:5000/api/student");
    setData(res.data);
  };

  return (
    <div className="App">  
      <DataTable data={data} />
    </div>
  );
}

The useState and useEffect functions come from React. We used both useEffect, useState from "react";

Create Student Form


1. Creating Student Entity and Form

In a student, an entity represents an object that encapsulates information about an individual student. Each student has various attributes that define their identity and details. In this case, the student entity has the following fields:

  • Name: Represents the name of the student.
  • Address: Represents the residential address of the student.
  • Date of Birth: Represents the birthdate of the student.
  • Gender: Represents the gender of the student. It can be categorized as male, female, or other.
  • Phone Number: This represents the contact number of the student.

Student details

Picture 4. Student entity ( name, address, date of birth, gender, and phone number)

2. Creating Form Step by Step

Now I’m creating a new file named 'studentForm.jsx' inside the 'component' folder.

Component

Picture 5. 'studentForm.jsx ‘ created.

Step 1. Initial student entity ( name, address, date of birth, gender, and phone number).

const initialValues = {
    name: "",
    address: "",
    dateOfBirth: "",
    gender: "",
    phoneNum: "",
  };

Step 2. Set the form value using useState.

  • const [formData, setFormData] = useState(initialValues);
  • Set the setFormData to initialValues

Step 3. Create a form

Now I’m going to create a student form using html, CSS, and hooks.

Simply I used HTML FORM with CSS i can suggest the tutorial on W3School.com. Let's start.

Certainly! Here's the formatted code:

```jsx
<form onSubmit={handleSubmit}>
  <div className="row">
    <label>
      Name:
      <input
        type="text"
        name="name"
        value={formData.name}
        onChange={handleChange}
      />
    </label>
    <label>
      Address:
      <input
        type="text"
        name="address"
        value={formData.address}
        onChange={handleChange}
      />
    </label>
  </div>

  <div className="row">
    <label>
      Date of Birth:
      <input
        type="date"
        name="dateOfBirth"
        value={formData.dateOfBirth}
        onChange={handleChange}
      />
    </label>

    <label>
      Gender:
      <select
        name="gender"
        value={formData.gender}
        onChange={handleChange}
      >
        <option value="">Select Gender</option>
        <option value="Male">Male</option>
        <option value="Female">Female</option>
      </select>
    </label>
  </div>

  <div className="row">
    <label>
      Phone Number:
      <input
        type="number"
        name="phoneNum"
        value={formData.phoneNum}
        onChange={handleChange}
      />
    </label>
  </div>
  <button type="submit">Submit</button>
</form>

Step 4. The onChange: This attribute is set to the handleChange function. It's called whenever the user types something in the input field. The purpose of this function is typically to update the state with the new value.

Here's an example of what handleChange might look like.

 const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

Step 5. The onSubmit: This attribute is set to the handleSubmit function. It will be called when the form is submitted, either by clicking a submit button or pressing Enter within a form field.

<form onSubmit={handleSubmit}> </form>

Here's an example of what handleSubmit might look like.

 const handleSubmit = async (e) => {
    e.preventDefault();
    const res = await axios
      .post("http://localhost:5000/api/student", formData)
      .then((res) => {
        console.log("crete", res.data);
         setFormData(initialValues);
      })
      .then((error) => {
        console.error("Error:", error);
      });
    console.log(formData);
  };
  • e.preventDefault(): This line prevents the default behavior of form submission, which would typically cause the page to reload. In React applications, it's common to handle form submissions manually to control the flow of the application.
  • const res = await axios.post("http://localhost:5000/api/student", formData): Here, uses the axios library to send a POST request to the specified API endpoint ("http://localhost:5000/api/student") with the form data (formData). The await keyword is used because axios.post returns a promise, and await is used to wait for the promise to resolve.

Step 6. Add submitted message successfully.

When submitting the form data and receiving a successful response, display the output message.

  1. destructuring assignment to create two variables (successMessage and setSuccessMessage) const [successMessage, setSuccessMessage] = useState("");
  2. Receiving a successful response and Set the success message setSuccessMessage("Data submitted successfully!");
  3. Clear success message after 3000 milliseconds (3 seconds) using the setTimeOut function.
    const handleSubmit = async (e) => {
      e.preventDefault();
      try {
        const res = await axios.post("http://localhost:5000/api/student", formData);
        console.log("create", res.data);
    
        setSuccessMessage("Data submitted successfully!");
    
        // Clear success message after 3000 milliseconds (3 seconds)
        setTimeout(() => {
          setSuccessMessage("");
        }, 3000);
    
        setFormData(initialValues);
      } catch (error) {
        console.error("Error:", error);
      }
    
      console.log(formData);
    };
    
  4. Add this line after the button tag, check the success message is true and the message will show.
    <button type="submit">Submit</button>
    {successMessage && <div className="success-message">{successMessage}</div>}
    

Here I’ll share the StudentForm.jsx.

import axios from "axios";
import React, { useState } from "react";
import "./style.css"; // Import the CSS file

const MyForm = () => {
  const initialValues = {
    name: "",
    address: "",
    dateOfBirth: "",
    gender: "",
    phoneNum: "",
  };
  const [formData, setFormData] = useState(initialValues);
  const [successMessage, setSuccessMessage] = useState("");

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const res = await axios
      .post("http://localhost:5000/api/student", formData)
      .then((res) => {
        console.log("crete", res.data);
        setSuccessMessage("Data submitted successfully!");
        // Clear success message after 3000 milliseconds (3 seconds)
        setTimeout(() => {
          setSuccessMessage("");
        }, 3000);

        setFormData(initialValues);
      })
      .then((error) => {
        console.error("Error:", error);
      });
    console.log(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div className="row">
        <label> Name:
          <input
            type="text"
            name="name"
            value={formData.name}
            onChange={handleChange}
          />
        </label>

        <label>  Address:
          <input
            type="text"
            name="address"
            value={formData.address}
            onChange={handleChange}
          />
        </label>
      </div>

      <div className="row">
        <label> Date of Birth:
          <input
            type="date"
            name="dateOfBirth"
            value={formData.dateOfBirth}
            onChange={handleChange}
          />
        </label>

        <label> Gender:
          <select name="gender" value={formData.gender} onChange={handleChange}>
            <option value="">Select Gender</option>
            <option value="Male">Male</option>
            <option value="Female">Female</option>
          </select>
        </label>
      </div>

      <div className="row">
        <label> Phone Number:
          <input
            type="number"
            name="phoneNum"
            value={formData.phoneNum}
            onChange={handleChange}
          />
        </label>
      </div>

      <button type="submit">Submit</button>
      {successMessage && (
        <div className="success-message">{successMessage}</div>
      )}
    </form>
  );
};

export default MyForm;

Step 7. Import the CSS.

form {
    max-width: 400px;
    margin: auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }
 
  .row {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
 
  label {
    flex: 1;
    display: block;
    margin-bottom: 8px;
  }
 
  input,
  select {
    width: 100%;
    padding: 8px;
    box-sizing: border-box;
  }
 
  button {
    background-color: #4caf50;
    color: white;
    padding: 10px 15px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
 
  button:hover {
    background-color: #45a049;
  }

Step 8. Import the StudentForm.jsx into the student.jsx.

import MyForm from "../component/studentForm";


      <MyForm />

Student

Picture 6. Import the StudentForm.jsx into the student.jsx.

Run the system npm start.


Student management system

Picture 7. Finally, we see the Student Management System table with form.

Submitting Form Data and Handling Success

Submit the form data {

    "name": "Kathiran",
    "address": "Colombo",
    "dateOfBirth": "1992-05-16",
    "gender": "Male",
    "phoneNum": "0713265245"
}

Student management system

Picture 8. Submit the form data.

Payload

Picture 09. When you click the submit button, send the payload with the endpoint post("http://localhost:5000/api/student", formData).

Data submitted

Picture 10. After clicking on the submit button, we receive a successful response and display the output message.

Conclusion

The 'Create' operation in React.js CRUD operations is a crucial aspect of data management. This comprehensive guide provides practical insights into creating forms, handling form submissions, and ensuring a seamless user experience in React applications. I have attached a zip file containing the source code for the Node.js API and React.js in this article.

This content is tailored for individuals interested in self-learning. Feel free to stay connected with me for more updates.


Adelanka (PVT) LTD
Globally based Software Developing & Data Processing Company