Building a Full-Stack Web Application with React and Node.js

 Building a Full-Stack Web Application with React and Node.js


Introduction

Full-stack web development is a popular topic among developers, and it can be challenging to build a complete web application from scratch. In this tutorial, we'll be using React and Node.js to build a full-stack web application that allows users to add, update, and delete items from a list.


Prerequisites

Before we get started, you'll need to have Node.js and npm installed on your machine. You'll also need a basic understanding of React and Node.js.


Setting up the Backend

Let's start by creating the backend for our application using Node.js and Express.


First, create a new directory for your project and run the following command to initialize a new Node.js project:


csharp


npm init -y

Next, install the necessary packages by running the following commands:


css


npm install express cors body-parser

npm install --save-dev nodemon

The express package is used to create a server, the cors package is used to enable cross-origin resource sharing, and the body-parser package is used to parse incoming request bodies. The nodemon package is a development dependency that will automatically restart our server when changes are made to our code.


Create a new file called server.js in the root directory of your project and add the following code:


javascript


const express = require('express');

const cors = require('cors');

const bodyParser = require('body-parser');


const app = express();


app.use(cors());

app.use(bodyParser.json());


const items = [];


app.get('/items', (req, res) => {

  res.send(items);

});


app.post('/items', (req, res) => {

  const newItem = req.body;

  items.push(newItem);

  res.send(newItem);

});


app.put('/items/:id', (req, res) => {

  const id = req.params.id;

  const updatedItem = req.body;

  const index = items.findIndex((item) => item.id === id);

  items[index] = { ...items[index], ...updatedItem };

  res.send(items[index]);

});


app.delete('/items/:id', (req, res) => {

  const id = req.params.id;

  const index = items.findIndex((item) => item.id === id);

  items.splice(index, 1);

  res.sendStatus(204);

});


const port = process.env.PORT || 5000;


app.listen(port, () => {

  console.log(`Server running on port ${port}`);

});

This code creates an Express server and sets up routes for handling GET, POST, PUT, and DELETE requests to an /items endpoint. The items array serves as our database for this simple application.


Start the server by running the following command:



npm run dev

This will start the server with nodemon, which will watch for changes to your code and automatically restart the server.


You can test the backend by visiting http://localhost:5000/items in your browser or using a tool like Postman to send requests to the server.


Setting up the Frontend

Next, let's create the frontend of our application using React.


First, create a new directory called client in the root directory of your project and navigate to it.


Then, initialize a new React project by running the following command:


lua


npx create-react-app .

This will create a new React project in the current directory.


Next, install the necessary packages by running the following command:



npm install axios

The axios package is used to make HTTP requests to our backend API.


Create a new file called `App.js in the src directory of your React project and replace the default code with the following:


javascript


import React, { useState, useEffect } from 'react';

import axios from 'axios';


function App() {

  const [items, setItems] = useState([]);

  const [newItem, setNewItem] = useState('');


  useEffect(() => {

    axios.get('/items')

      .then((response) => {

        setItems(response.data);

      })

      .catch((error) => {

        console.log(error);

      });

  }, []);


  const handleNewItemChange = (event) => {

    setNewItem(event.target.value);

  };


  const handleNewItemSubmit = (event) => {

    event.preventDefault();


    const item = {

      id: Math.random().toString(36).substr(2, 9),

      text: newItem,

    };


    axios.post('/items', item)

      .then((response) => {

        setItems([...items, response.data]);

        setNewItem('');

      })

      .catch((error) => {

        console.log(error);

      });

  };


  const handleItemUpdate = (id, updatedItem) => {

    axios.put(`/items/${id}`, updatedItem)

      .then((response) => {

        const index = items.findIndex((item) => item.id === id);

        const updatedItems = [...items];

        updatedItems[index] = response.data;

        setItems(updatedItems);

      })

      .catch((error) => {

        console.log(error);

      });

  };


  const handleItemDelete = (id) => {

    axios.delete(`/items/${id}`)

      .then(() => {

        const updatedItems = items.filter((item) => item.id !== id);

        setItems(updatedItems);

      })

      .catch((error) => {

        console.log(error);

      });

  };


  return (

    <div className="App">

      <h1>Full-Stack Todo List</h1>

      <form onSubmit={handleNewItemSubmit}>

        <input type="text" value={newItem} onChange={handleNewItemChange} />

        <button type="submit">Add Item</button>

      </form>

      <ul>

        {items.map((item) => (

          <li key={item.id}>

            <input type="text" value={item.text} onChange={(event) => handleItemUpdate(item.id, { text: event.target.value })} />

            <button onClick={() => handleItemDelete(item.id)}>Delete</button>

          </li>

        ))}

      </ul>

    </div>

  );

}


export default App;

This code sets up a basic todo list with a form for adding new items and a list of items that can be updated and deleted.


The useState hook is used to manage state in our component, and the useEffect hook is used to fetch the initial list of items from our backend API when the component mounts.


The axios library is used to make HTTP requests to our backend API when adding, updating, and deleting items.


Finally, render the App component by adding the following code to the index.js file in the src directory:


javascript


import React from 'react';

import ReactDOM from 'react-dom';

import App from './App';


ReactDOM.render(<App />, document.getElementById('root'));


Conclusion

Congratulations! You have successfully built a full-stack web application using React and Node.js. This is just the beginning of what you can do with full-stack development, and there is still a lot more to learn. Experiment with different technologies and features to create more complex and powerful applications.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...