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.
First, let’s ensure the frontend setup is ready within your MERN stack project.
cd frontend npm install axios
Axios will allow us to easily send requests to our Express API.
We’ll create components for managing users: a main component to list users and a form component for adding or editing users.
Inside src, create a components folder with the following files:
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;
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;
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;
To test the frontend UI with the backend API, make sure both the backend and frontend servers are running:
npm start
npm start
Visit http://localhost:3000 to interact with the application. You should be able to:
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!