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
Post a Comment