Public
Authored by Chriis Watson

Building a Full-Stack CRUD Application with ReactJS and Node.js: A Step-by-Step Guide

Building a web application can be a daunting task, especially if you're just getting started with web development. That's where CRUD applications come in handy. CRUD stands for Create, Read, Update, and Delete, and refers to the four basic operations that can be performed on a database. By building a CRUD application, you'll learn how to handle each of these operations and gain a solid foundation for more complex web development projects.

In this article, we'll walk you through the process of building a CRUD application using two popular technologies: ReactJS and Node.js. ReactJS is a JavaScript library for building user interfaces, while Node.js is a runtime environment for executing JavaScript code outside of a web browser. Together, they form a powerful combination for building web applications.

We'll start by setting up a new ReactJS project and a basic Node.js server with Express, a popular web framework for Node.js. We'll then connect the ReactJS frontend to the Node.js backend using Axios, a library for making HTTP requests. With the basic infrastructure in place, we'll walk you through building the Create, Read, Update, and Delete operations, step by step.

By the end of this article, you'll have a fully functional CRUD application that you can build upon and customize to suit your needs. So let's get started!

Setting up the project

To get started, we'll need to set up a new ReactJS project and a basic Node.js server with Express. We'll also connect the ReactJS frontend to the Node.js backend using Axios.

Creating a new ReactJS project

To create a new ReactJS project, we'll use the create-react-app tool, which is a popular way to quickly set up a new ReactJS project with a basic file structure and configuration. Here's how to create a new ReactJS project:

  1. Open up a terminal window.
  2. Navigate to the directory where you want to create your new ReactJS project.
  3. Run the following command: npx create-react-app my-project
  4. Wait for the project to be created. This may take a few minutes.
  5. Once the project is created, navigate into the project directory by running cd my-project.
  6. That's it! You now have a new ReactJS project set up and ready to go.
  7. Setting up a basic Node.js server with Express
  8. Next, we'll set up a basic Node.js server with Express. Express is a popular web framework for Node.js that makes it easy to create

HTTP servers and handle requests. Here's how to set up a basic Node.js server with Express: 1.Open up a terminal window. 2. Navigate to your ReactJS project directory if you're not already there. 3. Run the following command to create a new server.js file: touch server.js 4. Open the server.js file in your text editor of choice. 5. Add the following code to the server.js file: const express = require('express'); const app = express(); const port = 5000;

app.listen(port, () => { console.log(Server is running on port ${port}); });

This code sets up a new Express app and starts a server on port 5000. You can change the port number to any value you like, but make sure it doesn't conflict with any other running services on your machine.

Connecting the ReactJS frontend to the Node.js backend using Axios

Finally, we'll connect the ReactJS frontend to the Node.js backend using Axios. Axios is a library for making HTTP requests from the browser or Node.js. Here's how to connect the ReactJS frontend to the Node.js backend using Axios:

  1. Open the App.js file in your ReactJS project's src directory.
  2. Add the following code to the top of the file: import axios from 'axios';

const API_URL = 'http://localhost:5000';

This code imports Axios and sets a constant API_URL to the address of the Node.js server we just set up. Make sure the port number matches the one you set in the server.js file.

Now, we can use Axios to make HTTP requests to the Node.js server. For example, to send a GET request to the server, you could add the following code to a component's componentDidMount method: componentDidMount() { axios.get(${API_URL}/data).then(response => { console.log(response.data); }); } This code sends a GET request to the /data endpoint on the Node.js server and logs the response to the console. You can customize the endpoint and request type to match your needs.

That's it! You now have a basic ReactJS project with a Node.js server and Axios set up. In the next section, we'll start building the Create operation.

Building the Create operation

The first operation we'll build is Create, which involves adding new data to our database. We'll start by creating a form in ReactJS for adding new data. We'll then use Axios to send a POST request to the Node.js server, and finally, we'll write a server-side route in Express to handle the request and save the data to a database.

Creating a form in ReactJS for adding new data

To create a form in ReactJS, we'll use the useState hook to manage form input values and the handleSubmit method to handle form submissions. Here's how to create a form in ReactJS for adding new data: Open the App.js file in your ReactJS project's src directory. Add the following code to the top of the file: import React, { useState } from 'react'; This code imports the useState hook from the React library. Add the following code to the App function to set up a new state object for our form input values: const [formData, setFormData] = useState({ name: '', description: '', // Add any other form fields you need here });

This code sets up a new state object formData with initial values for each form field. You can customize the fields and initial values to match your needs.

Add the following code to the App function to set up a handleChange method that updates the form input values whenever they change: const handleChange = e => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; This code uses the spread operator to create a new object with the existing formData values and the updated value for the changed form field. Add the following code to the App function to set up a handleSubmit method that sends a POST request to the Node.js server when the form is submitted: const handleSubmit = e => { e.preventDefault(); axios.post(${API_URL}/data, formData).then(response => { console.log(response.data); }); };

This code uses Axios to send a POST request to the /data endpoint on the Node.js server with the current formData values. You can customize the endpoint to match your needs.

Finally, add the form JSX to the App function to render the form and handle user input:

Name: Description: Add Data

This code sets up a basic form with input fields for the name and description fields, along with a submit button. The onChange event handler calls the handleChange method to update the formData state whenever a user types into the input fields.

Using Axios to send a POST request to the Node.js server To send a POST request to the Node.js server when the user submits the form, we'll use Axios. Axios is a popular JavaScript library for making HTTP requests from the browser and Node.js. Open the App.js file in your ReactJS project's src directory. Add the following code to the top of the file: import axios from 'axios'; This code imports the Axios library. In the handleSubmit method we set up earlier, replace the console.log statement with the following code to send a POST request to the Node.js server: axios.post(${API_URL}/data, formData).then(response => { console.log(response.data); });

This code uses Axios to send a POST request to the /data endpoint on the Node.js server with the current formData values. The then method is used to handle the response from the server.

Replace the API_URL placeholder with the URL of your Node.js server. You can define the URL in a separate file or use an environment variable for security.

With these changes, the Create operation in our CRUD application is complete. When a user submits the form, a POST request is sent to the Node.js server with the new data. In the next section, we'll look at how to handle this request on the server side and save the data to a database.

Building the Read operation

The Read operation allows users to retrieve data from the database and display it in our CRUD application. To implement this functionality, we'll need to write a server-side route in Express to fetch the data from the database and send it to the ReactJS frontend, and create a ReactJS component to display the data in a table.

  1. Writing a server-side route to fetch the data

We'll start by creating a new route in our Node.js server to fetch the data from the database. This route will use the find method of the MongoDB Node.js driver to retrieve all the records from the data collection and send them as a JSON array to the ReactJS frontend.

javascript app.get('/data', (req, res) => { db.collection('data').find().toArray((err, result) => { if (err) { console.log(err); res.sendStatus(500); } else { res.json(result); } }); });

This code uses the find method of the MongoDB Node.js driver to retrieve all the records from the data collection and convert them to an array. The json method of the Express response object is used to send the array as a JSON response to the ReactJS frontend.

  1. Creating a ReactJS component to display the data

Next, we'll create a new ReactJS component called DataTable to display the data in a table. This component will use the useEffect hook to fetch the data from the Node.js server when the component mounts, and store the data in the component's state using the useState hook. The component will then render the data in a table using the map method.

function DataTable() { const [data, setData] = useState([]);

useEffect(() => { axios.get(${API_URL}/data).then(response => { setData(response.data); }); }, []);

return (

{data.map((item) => ( ))}
Name Email Actions
{item.name} {item.email} <button onClick={() => handleEdit(item)}>Edit <button onClick={() => handleDelete(item)}>Delete
); }

This code uses the useEffect hook to send a GET request to the Node.js server when the component mounts and update the component's state with the data received in the response. The map method is used to render each record in a table row, and the handleEdit and handleDelete functions are called when the user clicks the Edit or Delete buttons.

With these changes, the Read operation in our CRUD application is complete. The DataTable component will display all the records in the database in a table, and allow users to edit or delete each record by clicking the corresponding buttons. In the next section, we'll look at how to implement the Delete operation.

Building the Update operation

The Update operation allows users to modify existing data in our CRUD application. To implement this functionality, we'll need to create an Edit form in ReactJS, send a PUT request to the Node.js server with the updated data, and update the database record with the new values.

  1. Creating an Edit form in ReactJS

To create an Edit form, we'll start by reusing the DataForm component we created earlier. The DataForm component will take a prop called data which contains the existing data to be edited. We'll also need to update the form's title to "Edit Data" instead of "Add Data".

function EditDataForm(props) { const [formData, setFormData] = useState(props.data);

const handleSubmit = (event) => { event.preventDefault(); props.onSubmit(formData); };

const handleInputChange = (event) => { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; setFormData({...formData, [name]: value}); };

return (

Edit Data

Name:
Email:
Save ); }
  1. Sending a PUT request to the Node.js server

Next, we'll use Axios to send a PUT request to the Node.js server with the updated data. We'll need to pass the id of the record being updated as a parameter in the URL. axios.put(${API_URL}/data/${id}, formData).then(response => { console.log(response.data); });

This code sends a PUT request to the /data/:id endpoint on the Node.js server with the formData values. The :id parameter is replaced with the id of the record being updated.

  1. Updating the database record with the new values

Finally, we'll need to update the database record with the new values. We can reuse the updateData function we defined earlier in the Node.js server to handle the PUT request.

app.put('/data/:id', (req, res) => { const id = req.params.id; const data = req.body;

db.collection('data').updateOne({_id: ObjectId(id)}, {$set: data}, (err, result) => { if (err) { console.log(err); res.sendStatus(500); } else { res.sendStatus(200); } }); });

This code uses the updateOne method of the MongoDB Node.js driver to update the record with the new values. The ObjectId constructor is used to convert the id string to a MongoDB ObjectId.

With these changes, the Update operation in our CRUD application is complete. When a user clicks the Edit button, the Edit form is displayed with the existing data pre-populated. When the user submits the form, a PUT request is sent to the Node.js server with the updated data, and the database record is updated.

Building the Delete operation The Delete operation allows users to remove data from the database using our CRUD application. To implement this functionality, we'll need to write a server-side route in Express to delete the data from the database, and modify our ReactJS components to send a DELETE request to the server when the user clicks the Delete button.

  1. Writing a server-side route to delete the data

We'll start by creating a new route in our Node.js server to delete the data from the database. This route will use the deleteOne method of the MongoDB Node.js driver to remove the selected record from the data collection.

app.delete('/data/:id', (req, res) => { const { id } = req.params; const details = { '_id': new ObjectID(id) }; db.collection('data').deleteOne(details, (err, result) => { if (err) { console.log(err); res.sendStatus(500); } else { res.sendStatus(200); } }); });

This code uses the deleteOne method of the MongoDB Node.js driver to remove the selected record from the data collection using the _id field. The sendStatus method of the Express response object is used to send a 200 or 500 status code to the ReactJS frontend depending on the result of the operation.

  1. Modifying the ReactJS components to delete the data

Next, we'll modify the DataTable component to add a handleDelete function that sends a DELETE request to the Node.js server when the user clicks the Delete button. This function will use the axios library to send a DELETE request to the server, passing the _id field of the record to be deleted in the URL.

function DataTable() { // previous code... const handleDelete = (item) => { if (window.confirm('Are you sure you want to delete this item?')) { axios.delete(${API_URL}/data/${item._id}).then(response => { setData(data.filter(d => d._id !== item._id)); }); } }; // previous code... }

This code adds a new handleDelete function to the DataTable component that uses the window.confirm method to display a confirmation dialog to the user before deleting the item. If the user confirms the operation, the axios.delete method is used to send a DELETE request to the Node.js server with the _id of the item to be deleted. If the operation is successful, the setData method is used to remove the item from the data array in the component's state.

With these changes, the Delete operation in our CRUD application is complete. The DataTable component will allow users to delete records from the database by clicking the corresponding Delete button, and the data will be removed from both the database and the frontend.

Conclusion

In this article, we've covered the basics of building a CRUD application with ReactJS and Node.js. We started by creating a new ReactJS project using create-react-app and setting up a basic Node.js server with Express. We then connected the ReactJS frontend to the Node.js backend using Axios and implemented the Create, Read, Update, and Delete operations for our application.

By following the steps outlined in this article, you should now have a good understanding of how to build a basic CRUD application with ReactJS and Node.js. However, there is still much more to learn in this area, including how to handle more complex data structures, implement authentication and security features, and optimize performance.

If you're looking to build a more complex application using ReactJS and Node.js, you may want to hire react js developers who are experienced in building full-stack web applications. With the right team of developers, you can build a powerful, scalable, and secure application that meets your business needs and exceeds your users' expectations.

In summary, building a CRUD application with ReactJS and Node.js is a great way to get started with full-stack web development. With the right tools, knowledge, and expertise, you can build a powerful and scalable application that meets the needs of your users and helps you achieve your business goals.

Edited
reactj.rb 85 Bytes
  • Your post on "Building a Full-Stack CRUD Application with ReactJS and Node.js" was exceptional! Your clear explanations and practical examples made learning enjoyable. Thanks for sharing your expertise; it has inspired me to delve deeper into full-stack development. Looking forward to more of your insightful content.

    For more details visit us: Reactjs Training in Pune

Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment