React CRUD Application with a Backend API
In this tutorial, we’ll be building a simple React CRUD application using a backend API. Our application will allow users to create, view, update, and delete items from a list. Let’s get started! 🚀🔧💡
What is a React CRUD application? 📝💻🔄🗑️
CRUD stands for Create, Read, Update, and Delete. These are the four main things you can do with data in a database. A CRUD application is an application that provides an interface for users to perform these operations on data.
In our case, we’ll be building a simple application that allows users to manage a list of items. Users will be able to create new things, view existing items, update things, and delete items.
🛠️ Setting up the Development Environment
To begin, we need to prepare our development environment. Make sure you have installed the following programs:
Once you have these installed, open up your terminal and navigate to the directory where you want to create your project.
🚀 Creating a new React app
To create a new React app, Open your command prompt or terminal and navigate to the 📁 directory where you want to make your React app. Run the following command in your command prompt: ⌨️
npx create-react-app my-app
This will create a new directory called my-app
with all the necessary files to get started with a React app. Navigate into the my-app
directory and start the development server by running npm start
. You should see a message saying that the app is running on localhost:3000
. Open up your browser and navigate to that URL to see your app in action.
Now that we have our React app set up, let’s start building our CRUD functionality.
What is JSONPlaceholder?
JSONPlaceholder is a freely accessible REST API available for generating fictitious data. It serves various purposes, such as providing simulated information for a GitHub README, conducting demonstrations on CodeSandbox, supplying code samples on Stack Overflow, or facilitating local testing.
JSONPlaceholder is powered by JSON Server, which is a lightweight API server that serves JSON data. JSON Server is easy to install and use, and it doesn’t require any configuration.
JSONPlaceholder provides a variety of resources, including posts, users, albums, photos, and comments. Each resource has a set of attributes, which you can use to create realistic fake data.
For example, the posts
the resource has the following attributes:
- id
- title
- body
- userId
- createdAt
- updatedAt
You can use these attributes to create a fake post, such as:
{
"id": 1,
"title": "My First Post",
"body": "This is my first post.",
"userId": 1,
"createdAt": "2023-07-16T08:26:14Z",
"updatedAt": "2023-07-16T08:26:14Z"
}
JSONPlaceholder is a great resource for developers who need fake data for testing or prototyping. It’s easy to use, and it provides a variety of resources that you can use to create realistic fake data.
Here are some of the benefits of using JSONPlaceholder:
- It’s free to use.
- It’s easy to install and use.
- It doesn’t require any configuration.
- It provides a variety of resources.
- The data is realistic and up-to-date.
Fetching data from a backend API
We’ll be using a fake backend API for this tutorial, so we don’t have to worry about setting up a real backend. We’ll be using the JSONPlaceholder API, which provides us with fake data that we can use to test our application.
First, let’s create a new component for displaying our list of items. In the src
directory, create a new file called ItemList.js
and add the following code:
import React from 'react';
const ItemList = ({ items }) => {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
);
};
export default ItemList;
This is a simple functional component that takes in an array of items
props and displays them in an unordered list. Each item is displayed as a list item with its title the content.
Next, let’s update our App.js
file to fetch data from the JSONPlaceholder API and pass it down to our ItemList
component. Replace the contents App.js
with the following code:
import React, { useState, useEffect } from 'react';
import ItemList from './ItemList';
function App() {
const [items, setItems] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setItems(data));
}, []);
return (
<div className="App">
<h1>CRUD App</h1>
<ItemList items={items} />
</div>
);
}
export default App;
Here, we’re using the useState
and useEffect
hooks from React to manage our state and side effects. We’re initializing our state with an empty array of, which will be updated once we fetch data from the API.
In the useEffect
hook, we’re making a GET request to the /posts
endpoint of the JSONPlaceholder API. This returns an array of posts that we can use as our items. Once we receive the data, we update our state using the setItems
function.
Finally, we’re rendering our ItemList
component and passing down the items
array as props.
If you save your changes and refresh your app in the browser, you should see a list of items displayed on the page.
Adding functionality for creating new items
Next, let’s add some functionality for creating new items. We’ll need to add an input field and a button for submitting new items. Replace the existing code in your App.js file with the following:
import React, { useState, useEffect } from 'react';
import ItemList from './ItemList';
function App() {
const [items, setItems] = useState([]);
const [newItemTitle, setNewItemTitle] = useState('');
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setItems(data));
}, []);
const handleNewItemTitleChange = event => {
setNewItemTitle(event.target.value);
};
const handleNewItemSubmit = event => {
event.preventDefault();
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: newItemTitle,
body: '',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then(response => response.json())
.then(data => setItems([...items, data]));
setNewItemTitle('');
};
return (
<div className="App">
<h1>CRUD App</h1>
<form onSubmit={handleNewItemSubmit}>
<input
type="text"
value={newItemTitle}
onChange={handleNewItemTitleChange}
/>
<button type="submit">Add Item</button>
</form>
<ItemList items={items} />
</div>
);
}
export default App;
Here, we’re adding a new piece of state for tracking the value of our input field. We’re also adding two new event handlers: one for handling changes to the input field, and one for handling form submission.
In the handleNewItemTitleChange
function, we’re updating our newItemTitle
state with the current value of the input field.
In the handleNewItemSubmit
function, we’re preventing the default form submission behavior and making a POST request to the /posts
endpoint of the JSONPlaceholder API. We’re sending along the title of our new item in the request body. Once we receive a response from the API, we update our items
state with the new item and reset the newItemTitle
state to an empty string.
If you save your changes and refresh your app in the browser, you should see an input field and an “Add Item” button. Try entering a title for a new item and clicking the “Add Item” button. You should see your new item added to the list.
Adding functionality for updating items
Next, let’s add some functionality for updating items. We’ll need to add an “Edit” button to each item that allows us to update its title. Update your ItemList.js
file with the following code:
import React from 'react';
const ItemList = ({ items, onEdit }) => {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.title}{' '}
<button onClick={() => onEdit(item)}>Edit</button>
</li>
))}
</ul>
);
};
export default ItemList;
Here, we’re adding a new prop to our ItemList
component called onEdit
. This line of code will be executed when the user clicks the ‘Edit’ button.
We’re also adding an “Edit” button to each item. When this button is clicked, we call the onEdit
function and pass along the current item as an argument.
Next, let’s update our App.js
file to handle this new event. Please modify your App.js
file by adding the following code:
import React, { useState, useEffect } from 'react';
import ItemList from './ItemList';
function App() {
const [items, setItems] = useState([]);
const [newItemTitle, setNewItemTitle] = useState('');
const [editingItem, setEditingItem] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setItems(data));
}, []);
const handleNewItemTitleChange = event => {
setNewItemTitle(event.target.value);
};
const handleNewItemSubmit = event => {
event.preventDefault();
if (editingItem) {
fetch(`https://jsonplaceholder.typicode.com/posts/${editingItem.id}`, {
method: 'PUT',
body: JSON.stringify({
id: editingItem.id,
title: newItemTitle,
body: '',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then(response => response.json())
.then(data => {
setItems(
items.map(item => (item.id === data.id ? data : item))
);
setEditingItem(null);
setNewItemTitle('');
});
} else {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: newItemTitle,
body: '',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then(response => response.json())
.then(data => setItems([...items, data]));
setNewItemTitle('');
}
};
const handleEdit = item => {
setEditingItem(item);
setNewItemTitle(item.title);
};
const handleDelete = item => {
fetch(`https://jsonplaceholder.typicode.com/posts/${item.id}`, {
method: 'DELETE',
}).then(() => {
setItems(items.filter(i => i.id !== item.id));
});
};
return (
<div className="App">
<h1>CRUD App</h1>
<form onSubmit={handleNewItemSubmit}>
<input
type="text"
value={newItemTitle}
onChange={handleNewItemTitleChange}
/>
<button type="submit">
{editingItem ? 'Update Item' : 'Add Item'}
</button>
</form>
<ItemList items={items} onEdit={handleEdit} onDelete={handleDelete} />
</div>
);
}
export default App;
In this updated version of our App.js
file, we’re adding two new event handlers for handling editing and deleting items.
In the handleEdit
function, we’re updating our editingItem
state with the current item and set our input field’s value to the item’s title. This allows us to edit the item’s title in the input field.
In the handleDelete
function, we’re making a DELETE request to the /posts/:id
the endpoint of the JSONPlaceholder API, where :id
is the ID of the item we want to delete. Once we receive a response from the API, we update our items
state by removing the deleted item.
We’re also updating our handleNewItemSubmit
function to handle both creating and updating items. If we have an editingItem
, we make a PUT request to the /posts/:id
endpoint of the JSONPlaceholder API to update the article. Otherwise, we make a POST request to create a new thing as before.
Finally, we’re updating our JSX to pass down our new event handlers as props to our ItemList
component. We’re also updating the text of our submit button to say “Update Item” if we’re currently editing an item.
If you save your changes and refresh your app in the browser, you should see the “Edit” and “Delete” buttons next to each item. Try clicking these buttons to edit and delete items.
Putting it all together 📥🌐🔍
That’s it! We’ve built a simple React CRUD application using React and a backend API. Our application allows users to create, view, update, and delete items from a list.
You can continue to build on this foundation by adding more features and functionality to your app. For example, you could add validation to ensure that users enter valid data when creating or updating items. You could also add sorting and filtering functionality to make it easier for users to find specific items in the list.
Conclusion ✨🚀
In this tutorial, we’ve explored the exciting world of building a CRUD application using React and a backend API. 🌟 We’ve delved into the fundamental operations of a CRUD application, including creating ✨, reading 📖, updating 🔄, and deleting ❌ items.
With the power of React hooks, we’ve harnessed the ability to efficiently manage state and handle side effects within our application. The useState hook has allowed us to effortlessly handle local state, while the useEffect hook has empowered us to seamlessly fetch data from a backend API. 🎣
I sincerely hope that this tutorial has proven to be an invaluable resource, equipping you with the knowledge and skills to embark on your own journey of creating remarkable CRUD applications using React and a backend API. 🚀✨
May your coding adventures be filled with endless possibilities and may your applications flourish with seamless functionality! 🌈💻💡
React CRUD Application FAQ
1. What is a CRUD application?
A CRUD application is an application that provides an interface for users to perform the four basic operations on data in a database: Create, Read, Update, and Delete.
2. What tools do I need to build a React CRUD application with a backend API?
To build a CRUD application with React and a backend API, you’ll need to have Node.js, npm, and create-react-app installed on your computer.
3. How do I fetch data from a backend API in a React app?
You can fetch data from a backend API in a React app using the fetch
function. This function allows you to make HTTP requests to an API and receive data in response.
4. How do I update data in a backend API from a React app?
You can fetch data from a backend API in a React app using the fetch
function. This function allows you to make HTTP requests to an API and receive data in response.
How do I delete data from a backend API using a React app?
You can delete data from a backend API using a React app by making an HTTP DELETE request to the appropriate endpoint of the API.