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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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

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

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

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

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.

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

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