Skip to main content

React js CRUD Example Step by Step

How to build basic CRUD app with ReactJS

Here's an example of building a simple CRUD application for managing a list of books.

Step 1: Set up the React application

To set up the React application, you'll need to have Node.js and NPM installed on your computer. Open a terminal or command prompt and create a new directory for your project.

mkdir react-crud-app cd react-crud-app

Next, initialize a new React application using the create-react-app CLI.

npx create-react-app .

Step 2: Create a list of books

In this step, you'll create a list of books and display them in a table. Create a new file BookList.js in the src directory and add the following code:

import React from 'react'; const BookList = ({ books }) => { return ( <table> <thead> <tr> <th>Title</th> <th>Author</th> <th>Actions</th> </tr> </thead> <tbody> {books.map((book) => ( <tr key={book.id}> <td>{book.title}</td> <td>{book.author}</td> <td> <button>Edit</button> <button>Delete</button> </td> </tr> ))} </tbody> </table> ); }; export default BookList;

Here, the BookList component takes a books prop which is an array of books. It then maps over the books and renders them in a table.

Step 3: Create a form for adding books

In this step, you'll create a form for adding new books. Create a new file AddBook.js in the src directory and add the following code:

import React, { useState } from 'react'; const AddBook = ({ onAdd }) => { const [title, setTitle] = useState(''); const [author, setAuthor] = useState(''); const handleSubmit = (e) => { e.preventDefault(); const book = { title, author }; onAdd(book); setTitle(''); setAuthor(''); }; return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Title" value={title} onChange={(e) => setTitle(e.target.value)} /> <input type="text" placeholder="Author" value={author} onChange={(e) => setAuthor(e.target.value)} /> <button>Add</button> </form> ); }; export default AddBook;

Here, the AddBook component takes an onAdd prop which is a function that will be called when the form is submitted. It has two local state variables, title and author, which are used to store the input values. When the form is submitted, it creates a new book object and calls the onAdd function with the book data.

Step 4: Create a parent component

In this step, you'll create a parent component that will manage the state of the application and pass it down to the child components. Create a new file App.js in the src directory and add the following code:

import React, { useState } from 'react'; import BookList from './BookList'; import AddBook from './AddBook'; const App = () => { const [books, setBooks] = useState([]); const handleAdd = (book) => { setBooks([...books, book]); }; const handleDelete = (id) => { setBooks(books.filter((book) => book.id !== id)); }; const handleUpdate = (id, updatedBook) => { setBooks( books.map((book) => (book.id === id ? { ...book, ...updatedBook } : book)) ); }; return ( <div> <h1>Book List</h1> <BookList books={books} onDelete={handleDelete} onUpdate={handleUpdate} /> <AddBook onAdd={handleAdd} /> </div> ); }; export default App;

Here, the App component initializes the books state as an empty array and defines three callback functions: handleAdd, handleDelete, and handleUpdate. These functions will be passed down to the child components as props.

The App component also renders the BookList and AddBook components, passing in the books state and the callback functions as props.

Step 5: Implement CRUD functionality

In this step, you'll add CRUD functionality to the application by implementing the handleDelete and handleUpdate functions. Update the BookList component in BookList.js to the following code:

import React from 'react'; const BookList = ({ books, onDelete, onUpdate }) => { const handleDelete = (id) => { onDelete(id); }; const handleUpdate = (id, book) => { onUpdate(id, book); }; return ( <table> <thead> <tr> <th>Title</th> <th>Author</th> <th>Actions</th> </tr> </thead> <tbody> {books.map((book) => ( <tr key={book.id}> <td>{book.title}</td> <td>{book.author}</td> <td> <button onClick={() => handleUpdate(book.id, book)}>Edit</button> <button onClick={() => handleDelete(book.id)}>Delete</button> </td> </tr> ))} </tbody> </table> ); }; export default BookList;

Here, the BookList component now takes two additional props: onDelete and onUpdate, which are callback functions passed down from the App component. When the delete or update button is clicked, the corresponding function is called with the book's id and book data.

Update the handleDelete and handleUpdate functions in App.js to the following code:

const handleDelete = (id) => { setBooks(books.filter((book) => book.id !== id)); }; const handleUpdate = (id, updatedBook) => { setBooks( books.map((book) => (book.id === id ? { ...book, ...updatedBook } : book)) ); };

Here, the handleDelete function removes the book with the specified id from the books array using the filter method.

The handleUpdate function updates the book with the specified id in the books array using the map method. It creates a new array with the updated book data and all the other books with their original data.

Step 6: Add Form Validation

In this step, you'll add form validation to the AddBook component. Update the AddBook component in AddBook.js to the following code:

import React, { useState } from 'react'; const AddBook = ({ onAdd }) => { const [title, setTitle] = useState(''); const [author, setAuthor] = useState(''); const [titleError, setTitleError] = useState(''); const [authorError, setAuthorError] = useState(''); const handleSubmit = (e) => { e.preventDefault(); if (!title) { setTitleError('Please enter a title'); return; } if (!author) { setAuthorError('Please enter an author'); return; } const newBook = { id: Date.now(), title, author }; onAdd(newBook); setTitle(''); setAuthor(''); }; const handleTitleChange = (e) => { setTitle(e.target.value); setTitleError(''); }; const handleAuthorChange = (e) => { setAuthor(e.target.value); setAuthorError(''); }; return ( <form onSubmit={handleSubmit}> <input type="text" placeholder="Title" value={title} onChange={handleTitleChange} /> {titleError && <span style={{ color: 'red' }}>{titleError}</span>} <br /> <input type="text" placeholder="Author" value={author} onChange={handleAuthorChange} /> {authorError && <span style={{ color: 'red' }}>{authorError}</span>} <br /> <button type="submit">Add Book</button> </form> ); }; export default AddBook;

Here, the AddBook component defines four state variables: title, author, titleError, and authorError. The handleSubmit function is called when the form is submitted. It first checks if the title and author fields are empty and displays an error message if they are. If both fields have a value, it creates a new book object with the current title and author values and a unique id. It then calls the onAdd callback function passed down from the App component with the new book object and resets the title and author state variables.

The handleTitleChange and handleAuthorChange functions are called when the corresponding input fields are changed. They update the title and author state variables and reset the corresponding error state variable.

The input fields also display error messages if the corresponding error state variable is not empty.

Step 7: Styling

In this step, you'll add some basic styling to the application. Add the following code to the index.css file:

body { font-family: Arial, sans-serif; } h1 { text-align: center; } table { border-collapse: collapse; width: 100%; max-width: 800px; margin: 0 auto; } th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd; } th { background-color: #f2f2f2; } tr:hover { background-color: #f2f2f2; } form { display: flex; flex-direction: column; max-width: 400px; margin: 0 auto; } input[type='text'] {
margin-bottom: 10px;
padding: 8px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px;
}

span { font-size: 14px; margin-top: 4px; }

Step 8: Running the Application

To run the application, open a terminal window in the project directory and run the following command:

npm start

This will start the development server and open the application in a web browser at http://localhost:3000.

In this tutorial, you learned how to create a simple CRUD application using React.js. You started by setting up a new React project using create-react-app. You then created a book list component, an add book component, and implemented CRUD functionality using state management. You also added form validation and basic styling to the application. Finally, you ran the application and saw the results in a web browser.

Comments

Popular posts from this blog

Angular 14 CRUD Operation with Web API .Net 6.0

How to Perform CRUD Operation Using Angular 14 In this article, we will learn the angular crud (create, read, update, delete) tutorial with ASP.NET Core 6 web API. We will use the SQL Server database and responsive user interface for our Web app, we will use the Bootstrap 5. Let's start step by step. Step 1 - Create Database and Web API First we need to create Employee database in SQL Server and web API to communicate with database. so you can use my previous article CRUD operations in web API using net 6.0 to create web API step by step. As you can see, after creating all the required API and database, our API creation part is completed. Now we have to do the angular part like installing angular CLI, creating angular 14 project, command for building and running angular application...etc. Step 2 - Install Angular CLI Now we have to install angular CLI into our system. If you have already installed angular CLI into your system then skip this step.  To install angular CLI open vis

Angular 14 : 404 error during refresh page after deployment

In this article, We will learn how to solve 404 file or directory not found angular error in production.  Refresh browser angular 404 file or directory not found error You have built an Angular app and created a production build with ng build --prod You deploy it to a production server. Everything works fine until you refresh the page. The app throws The requested URL was not found on this server message (Status code 404 not found). It appears that angular routing not working on the production server when you refresh the page. The error appears on the following scenarios When you type the URL directly in the address bar. When you refresh the page The error appears on all the pages except the root page.   Reason for the requested URL was not found on this server error In a Multi-page web application, every time the application needs to display a page it has to send a request to the web server. You can do that by either typing the URL in the address bar, clicking on the Menu link/

CRUD operations in web api using net 6.0

.NET 6.0 - CRUD API Example and Tutorial This tutorial gives you step by step implementation of creating CRUD operations using ASP.NET Web API Core. This tutorial builds API for its clients to manage employee. it shows how to configure the SQL server connection to manage CRUD operations in real-time applications. Let's start step by step. 1. Create ASP.NET Web API Project Open your Visual Studio and select New Project from File Menu.     Now enter the name of the application and click next.   Next select framework .net 6 from drop down and enable open API (Swagger) support and click on create to create default project template for API.   2. Now Add Model to Employee Web API In this step, you will add the Employee Model Class which will define database entity. Right click on the project from solution explorer and select Add -> New Folder . Enter folder name as Models . Right click on the Models folder and select Add -> Class and add class file with name