国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end JS Tutorial The MERN stack series !

The MERN stack series !

Nov 15, 2024 am 04:52 AM

The MERN stack series !

Post 5: Building the Frontend User Interface with React

In Post 4, we developed a RESTful API using Express and Node.js to handle CRUD operations for user data. Now, it’s time to create the frontend UI using React, allowing users to view, add, update, and delete data through an interactive interface that communicates with our backend.

1. Setting Up the Frontend Project

First, let’s ensure the frontend setup is ready within your MERN stack project.

  • Navigate to the frontend folder and install Axios for handling HTTP requests:
  cd frontend
  npm install axios

Axios will allow us to easily send requests to our Express API.

2. Creating Basic React Components

We’ll create components for managing users: a main component to list users and a form component for adding or editing users.

Organize Components Folder

Inside src, create a components folder with the following files:

  • UserList.js - to list users
  • UserForm.js - for creating and editing users

UserList Component

UserList will fetch user data from the backend and display it in a list. Add the following code to UserList.js:

// src/components/UserList.js
import React, { useState, useEffect } from "react";
import axios from "axios";

const UserList = ({ onEdit, onDelete }) => {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await axios.get("/api/users");
        setUsers(response.data);
      } catch (error) {
        console.error("Error fetching users:", error);
      }
    };
    fetchUsers();
  }, []);

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map(user => (
          <li key={user._id}>
            {user.name} - {user.email}
            <button onClick={() => onEdit(user)}>Edit</button>
            <button onClick={() => onDelete(user._id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default UserList;

UserForm Component

The UserForm component handles creating and updating users.

// src/components/UserForm.js
import React, { useState, useEffect } from "react";
import axios from "axios";

const UserForm = ({ selectedUser, onSave }) => {
  const [formData, setFormData] = useState({ name: "", email: "", password: "" });

  useEffect(() => {
    if (selectedUser) {
      setFormData(selectedUser);
    }
  }, [selectedUser]);

  const handleChange = e => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async e => {
    e.preventDefault();
    try {
      if (selectedUser) {
        await axios.put(`/api/users/${selectedUser._id}`, formData);
      } else {
        await axios.post("/api/users", formData);
      }
      onSave();
      setFormData({ name: "", email: "", password: "" });
    } catch (error) {
      console.error("Error saving user:", error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" value={formData.name} onChange={handleChange} placeholder="Name" required />
      <input name="email" value={formData.email} onChange={handleChange} placeholder="Email" required />
      <input name="password" value={formData.password} onChange={handleChange} placeholder="Password" required />
      <button type="submit">{selectedUser ? "Update User" : "Add User"}</button>
    </form>
  );
};

export default UserForm;

3. Putting It All Together in the App Component

In App.js, we’ll combine UserList and UserForm to display the list of users and handle adding/updating users.

// src/App.js
import React, { useState } from "react";
import UserList from "./components/UserList";
import UserForm from "./components/UserForm";
import axios from "axios";

const App = () => {
  const [selectedUser, setSelectedUser] = useState(null);

  const handleEdit = user => setSelectedUser(user);

  const handleDelete = async userId => {
    try {
      await axios.delete(`/api/users/${userId}`);
      window.location.reload();
    } catch (error) {
      console.error("Error deleting user:", error);
    }
  };

  const handleSave = () => {
    setSelectedUser(null);
    window.location.reload();
  };

  return (
    <div>
      <h1>Manage Users</h1>
      <UserForm selectedUser={selectedUser} onSave={handleSave} />
      <UserList onEdit={handleEdit} onDelete={handleDelete} />
    </div>
  );
};

export default App;

4. Testing the Application

To test the frontend UI with the backend API, make sure both the backend and frontend servers are running:

  • In the backend folder, start the server:
  npm start
  • In the frontend folder, start the React app:
  npm start

Visit http://localhost:3000 to interact with the application. You should be able to:

  • Add a new user: Enter details in the form and click "Add User."
  • Edit a user: Click "Edit" next to a user’s name to load their data in the form.
  • Delete a user: Click "Delete" to remove the user from the list.

Next Steps

In Post 6, we’ll focus on refining the UI and improving the user experience by adding styling and handling form validations. Stay tuned for more!

The above is the detailed content of The MERN stack series !. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java vs. JavaScript: Clearing Up the Confusion Java vs. JavaScript: Clearing Up the Confusion Jun 20, 2025 am 12:27 AM

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

Mastering JavaScript Comments: A Comprehensive Guide Mastering JavaScript Comments: A Comprehensive Guide Jun 14, 2025 am 12:11 AM

CommentsarecrucialinJavaScriptformaintainingclarityandfosteringcollaboration.1)Theyhelpindebugging,onboarding,andunderstandingcodeevolution.2)Usesingle-linecommentsforquickexplanationsandmulti-linecommentsfordetaileddescriptions.3)Bestpracticesinclud

Javascript Comments: short explanation Javascript Comments: short explanation Jun 19, 2025 am 12:40 AM

JavaScriptcommentsareessentialformaintaining,reading,andguidingcodeexecution.1)Single-linecommentsareusedforquickexplanations.2)Multi-linecommentsexplaincomplexlogicorprovidedetaileddocumentation.3)Inlinecommentsclarifyspecificpartsofcode.Bestpractic

JavaScript Data Types: A Deep Dive JavaScript Data Types: A Deep Dive Jun 13, 2025 am 12:10 AM

JavaScripthasseveralprimitivedatatypes:Number,String,Boolean,Undefined,Null,Symbol,andBigInt,andnon-primitivetypeslikeObjectandArray.Understandingtheseiscrucialforwritingefficient,bug-freecode:1)Numberusesa64-bitformat,leadingtofloating-pointissuesli

JavaScript vs. Java: A Comprehensive Comparison for Developers JavaScript vs. Java: A Comprehensive Comparison for Developers Jun 20, 2025 am 12:21 AM

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

How to work with dates and times in js? How to work with dates and times in js? Jul 01, 2025 am 01:27 AM

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

JavaScript: Exploring Data Types for Efficient Coding JavaScript: Exploring Data Types for Efficient Coding Jun 20, 2025 am 12:46 AM

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

Why should you place  tags at the bottom of the ? Why should you place tags at the bottom of the ? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

See all articles