DEV Community

bilal khan
bilal khan

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • In the frontend folder, start the React app:
  npm start
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)