Enhancing UserList Component with Edit User Functionality

Enhancing UserList Component with Edit User Functionality

Title: Enhancing UserList Component with Edit User Functionality

                 Welcome to CodecraftersCampus! In this blog post, we’ll walk you through enhancing your existing UserList component in React by adding functionality to edit existing users. We’ll also apply some styling to make the component look polished and user-friendly. If you haven’t seen the previous tutorial on creating the UserList component, be sure to check it out.

Overview of the Enhancement

In this tutorial, we will:

  • Add an edit button for each user in the UserList component.
  • Populate the form with the user’s data for editing.
  • Implement functionality to update the user’s information.
  • Style the user list and form for a better user experience.

Step 1: Initial Setup

First, we need to add state management for editing users. Initialize the editingUser state variable and set up the basic structure for handling user edits.

UserList.js:

				
					import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './UserList.css';

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [newUser, setNewUser] = useState({
    username: '',
    email: '',
    phone: '',
    password: ''
  });
  const [editingUser, setEditingUser] = useState(null);

  useEffect(() => {
    axios.get('http://localhost:5000/api/users')
      .then(response => {
        setUsers(response.data);
      })
      .catch(error => {
        console.error('There was an error fetching the users!', error);
      });
  }, []);

  const handleChange = (e) => {
    const { name, value } = e.target;
    if (editingUser) {
      setEditingUser({ ...editingUser, [name]: value });
    } else {
      setNewUser({ ...newUser, [name]: value });
    }
  };
}

				
			

Step 2: Form Submission Logic

Add the logic to handle form submissions for both adding and updating users.

UserList.js:

				
					  const handleAddUser = (e) => {
    e.preventDefault();
    const newId = users.length > 0 ? Math.max(...users.map(user => user.id)) + 1 : 1;
    const userToAdd = { ...newUser, id: newId };

    axios.post('http://localhost:5000/api/users', userToAdd)
      .then(response => {
        setUsers([...users, userToAdd]);
        setNewUser({ username: '', email: '', phone: '', password: '' });
      })
      .catch(error => {
        console.error('There was an error adding the user!', error);
      });
  };

  const handleUpdateUser = (e) => {
    e.preventDefault();
    axios.put(`http://localhost:5000/api/users/${editingUser.id}`, editingUser)
      .then(response => {
        setUsers(users.map(user => (user.id === editingUser.id ? editingUser : user)));
        setEditingUser(null);
      })
      .catch(error => {
        console.error('There was an error updating the user!', error);
      });
  };

  const handleCancelEdit = () => {
    setEditingUser(null);
  };

				
			

Step 3: Adding the Edit Button

Add an edit button for each user in the user list and handle the editing logic.

UserList.js:

				
					  const handleEditUser = (user) => {
    setEditingUser(user);
  };

  return (
    <div className="user-list-container">
      <h2>User List</h2>
      <table className="user-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Username</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {users.map(user => (
            <tr key={user.id}>
              <td>{user.id}</td>
              <td>{user.username}</td>
              <td>{user.email}</td>
              <td>{user.phone}</td>
              <td>
                <button onClick={() => handleEditUser(user)}>Edit</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

				
			

Step 4: Updating the Form

Update the form to handle both adding and editing users.

UserList.js:

				
					      <h2>{editingUser ? 'Edit User' : 'Add New User'}</h2>
      <form onSubmit={editingUser ? handleUpdateUser : handleAddUser} className="add-user-form">
        <input
          type="text"
          name="username"
          placeholder="Username"
          value={editingUser ? editingUser.username : newUser.username}
          onChange={handleChange}
          required
        />
        <input
          type="email"
          name="email"
          placeholder="Email"
          value={editingUser ? editingUser.email : newUser.email}
          onChange={handleChange}
          required
        />
        <input
          type="tel"
          name="phone"
          placeholder="Phone"
          value={editingUser ? editingUser.phone : newUser.phone}
          onChange={handleChange}
          required
        />
        <input
          type="password"
          name="password"
          placeholder="Password"
          value={editingUser ? editingUser.password : newUser.password}
          onChange={handleChange}
          required
        />
        <button type="submit">{editingUser ? 'Update User' : 'Add User'}</button>
        {editingUser && <button type="button" onClick={handleCancelEdit}>Cancel</button>}
      </form>
    </div>
  );
};

export default UserList;

				
			

Step 5: Styling the Component

Add styles to make the component look polished.

UserList.css:

				
					/* style for the user list container */
.user-list-container {
  padding: 20px;
  margin: 0 auto;
  max-width: 800px;
}

/* style for the heading */
.user-list-container h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

/* style for the user table */
.user-table {
  width: 100%;
  border-collapse: collapse;
  margin: 0 auto;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* style for table cells */
.user-table th, .user-table td {
  padding: 12px;
  border: 1px solid #ddd;
  text-align: left;
}

/* style for table header cells */
.user-table th {
  background-color: #f4f4f4;
  color: #333;
}

/* style for alternating row colors */
.user-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

/* style for row hover effect */
.user-table tr:hover {
  background-color: #f1f1f1;
}

/* style for the add user form */
.add-user-form {
  display: flex;
  flex-direction: column;
  max-width: 400px;
  margin: 20px auto;
}

/* style for form inputs */
.add-user-form input {
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

/* style for the submit button */
.add-user-form button {
  padding: 10px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

/* style for button hover effect */
.add-user-form button:hover {
  background-color: #218838;
}

/* style for the cancel button */
.add-user-form button[type="button"] {
  background-color: #dc3545;
}

/* style for the cancel button hover effect */
.add-user-form button[type="button"]:hover {
  background-color: #c82333;
}

				
			

Running the Application

Now it’s time to run our application. Open your terminal and run:

				
					npm start

				
			

Open your browser and navigate to http://localhost:3000. You should see the user list with an edit button for each user, and a form that switches between adding a new user and editing an existing user. When you click the edit button, the form will populate with the user’s data, allowing you to update their information.

                  In this post, we enhanced the UserList component by adding edit functionality. We implemented state management and form logic for editing users, and styled the component for a polished look. Finally, we verified the functionality by running the application.

Overview

Leave a Reply

Your email address will not be published. Required fields are marked *

Enquire Now