×

Introduction

To create a CRUD application is the best way to learn how to work with React.js. This article guides you through the process of building a React.js application.

CRUD

CRUD is a standardized mechanism to interact with data in a database. It stands for Create, Read, Update and Delete operations that are fundamental to web applications.

CRUD operations are commonly implemented in the backend code to interact with a database. In the context of RESTful APIs, these operations are mapped to specific HTTP methods.

  • Create: Adding of new data or records into the database.
  • The client needs to send a POST HTTP request to the server’s endpoint with user data. The server processes this request and adds the new user to the database.

  • Read: Retrieving data from the database. It is used to view specific data.
  • To fetch the data, send a GET HTTP request to GET /users/{id}. The server responds with the requested data. Update: Modifying existing data in the database.

    Send a PUT or PATCH HTTP request to perform modification. The server processes the request and updates the user in the database. PUT replaces the entire resource with the updated data. PATCH partially updates the resource with the provided data.

  • Delete: Removing data from the database.
  • To delete a user, the client sends a DELETE HTTP request to DELETE /users/{id}. The server processes the request and removes the user or data from the database.

Set up the development environment

Install Node.js and npm to run and manage the React applications. Node.js is a server-side runtime environment. npm (Node Package Manager) is the package manager that allows you to install and manage libraries and dependencies for the projects. Download Node.js from the official Node.js website.

Guide to Building a React.js CRUD Application

  • Step 1: Setting Up the React Application
  • Install Create React App, the environment for building single-page applications using the following command. Navigate into the new project directory.

    npx create-react-app react-crud-app cd react-crud-app start the development server: npm start
  • Step 2: Setting Up the Project Structure
  • Plan the layout of the CRUD application by organizing project structure. UI components are essential for building the user interface of the application. The common structure of any CRUD application is

    src/ ├── components/ │ ├── AddUser.js │ ├── EditUser.js │ ├── UserList.js ├── App.js ├── index.js
  • Step 3: Creating the User Component
  • Create a UserList component to display the list of users.

    // src/components/UserList.js import React, { useState, useEffect } from react; import axios from axios; const UserList = () => { const [users, setUsers] = useState([]); useEffect(() => { loadUsers(); }, []); const loadUsers = async () => { const result = await axios.get(http://localhost:3001/users); setUsers(result.data); }; return ( <div> <h3>User List</h3> <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> </div> ); }; export default UserList;

    Create AddUser Component:

    This component will handle the CRUD Operation of adding a new user.

    // src/components/AddUser.js import React, { useState } from react; import axios from axios; const AddUser = () => { const [name, setName] = useState(); const handleSubmit = async (e) => { e.preventDefault(); await axios.post(http://localhost:3001/users, { name }); setName(); }; return ( <form onSubmit={handleSubmit}> <div> <label>Name</label> <input type="text" value={name} onChange={(e)=> setName(e.target.value)} /> </div> <button type="submit">Add User</button> </form> ); }; export default AddUser;

    Create EditUser Component:

    Editing an existing user can be handled by this component.

    / src/components/EditUser.js import React, { useState, useEffect } from react; import axios from axios; import { useParams } from react-router-dom; const EditUser = () => { const { id } = useParams(); const [name, setName] = useState(); useEffect(() => { loadUser(); }, []); const loadUser = async () => { const result = await axios.get(`http://localhost:3001/users/${id}`); setName(result.data.name); }; const handleSubmit = async (e) => { e.preventDefault(); await axios.put(`http://localhost:3001/users/${id}`, { name }); }; return ( <form onSubmit={handleSubmit}> <div> <label>Name</label> <input type="text" value={name} onChange={(e)=> setName(e.target.value)} /> </div> <button type="submit">Update User</button> </form> ); }; export default EditUser;
  • Step 4: Setting Up Routing
  • set up a React Router for navigating between different components.

    Install React Router: npm install react-router-dom

    Update App Component:

    // src/components/AddUser.js import React, { useState } from react; import axios from axios; const AddUser = () => { const [name, setName] = useState(); const handleSubmit = async (e) => { e.preventDefault(); await axios.post(http://localhost:3001/users, { name }); setName(); }; return ( <form onSubmit={handleSubmit}> <div> <label>Name</label> <input type="text" value={name} onChange={(e)=> setName(e.target.value)} /> </div> <button type="submit">Add User</button> </form> ); }; export default AddUser; p><strong> Create a db.json File: </strong></p>

    Start JSON Server:

    json-server watch db.json port 3001 Step 6: Delete functionality

    Add delete functionality to the UserList component.

    // src/components/UserList.js //const deleteUser = async (id) => { awaitaxios.delete(`http://localhost:3001/users/${id}`); loadUsers(); }; return ( <div> <h3>User List</h3> <ul> {users.map(user => ( <li key={user.id}> {user.name} <button onClick={()=> deleteUser(user.id)}>Delete</button> </li> ))} </ul> </div> );
  • Add basic styling to make the application more presentable using basic CSS.

    /* src/App.css */ body { font-family: Arial, sans-serif; } form { margin-bottom: 20px; } ul { list-style-type: none; padding: 0; } li { padding: 5px 0; } Import CSS: Import the CSS file in App.js. // src/App.js import ./App.css; //

    Conclusion

    To wrap up, the basic React.js CRUD application has been built successfully using JSON Server for the backend. This application includes components for listing users, adding a new user, editing an existing user, and deleting a user. Enhance this application by adding more features, such as form validation, better error handling, and more advanced styling. To learn and experience how to build React.js applications, join Credo Systemz React JS Training in Chennai.

    Join Credo Systemz Software Courses in Chennai at Credo Systemz OMR, Credo Systemz Velachery to kick-start or uplift your career path.