Creating, editing, and viewing contact details in a React application involves designing intuitive and user-friendly components. Below is a detailed breakdown of how you might structure each of these components in your application.
Create/Edit Contact Page
The Create/Edit page can be a single form that shares a similar structure. The component can determine whether it’s creating a new contact or editing an existing one based on whether a contact is passed as a prop. Below is a sample implementation:
ContactForm Component
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const ContactForm = ({ contact, onSave, onCancel }) => {
const [formData, setFormData] = useState({ name: '', email: '' });
useEffect(() => {
if (contact) {
setFormData(contact); // Load existing contact for editing
}
}, [contact]);
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
onSave(formData); // Call parent save function with the form data
};
return (
<div>
<h2>{contact ? 'Edit Contact' : 'Create Contact'}</h2>
<form onSubmit={handleSubmit}>
<div>
<label>
Name:
<input
type="text"
name="name"
value={formData.name}
onChange={handleInputChange}
required
/>
</label>
</div>
<div>
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleInputChange}
required
/>
</label>
</div>
<div>
<button type="submit">{contact ? 'Update' : 'Create'}</button>
<button type="button" onClick={onCancel}>Cancel</button>
</div>
</form>
</div>
);
};
export default ContactForm;
Viewing Contact Details
The contact viewing page should present all the information related to a specific contact in a read-only format. You could create a ContactDetail component that displays this information.
ContactDetail Component
import React from 'react';
const ContactDetail = ({ contact, onEdit, onDelete }) => {
if (!contact) {
return <p>No contact selected.</p>;
}
return (
<div>
<h2>Contact Details</h2>
<div>
<strong>ID:</strong> {contact.id}
</div>
<div>
<strong>Name:</strong> {contact.name}
</div>
<div>
<strong>Email:</strong> {contact.email}
</div>
<div>
<button onClick={onEdit}>Edit</button>
<button onClick={() => onDelete(contact.id)}>Delete</button>
</div>
</div>
);
};
export default ContactDetail;
Integrating Create/Edit/Detail in ContactGridView
Now you can integrate these components into your ContactGridView so that when a user clicks on a contact, they can view or edit details, or create a new contact.
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import ContactForm from './ContactForm';
import ContactDetail from './ContactDetail';
const ContactGridView = () => {
const [contacts, setContacts] = useState([]);
const [currentPage, setCurrentPage] = useState(0);
const [pageSize, setPageSize] = useState(10);
const [totalCount, setTotalCount] = useState(0);
const [selectedContact, setSelectedContact] = useState(null);
const [isEditing, setIsEditing] = useState(false);
useEffect(() => {
fetchContacts();
}, [currentPage, pageSize]);
const fetchContacts = async () => {
try {
const response = await axios.get('http://your-yii2-app-url/api/contact', {
params: { page: currentPage, pageSize },
});
setContacts(response.data.items);
setTotalCount(response.data.totalCount);
} catch (error) {
console.error("Error fetching contacts", error);
}
};
const handleDelete = async (id) => {
try {
await axios.delete(`http://your-yii2-app-url/api/contact/${id}`);
fetchContacts();
setSelectedContact(null); // Clear selected contact after deletion
} catch (error) {
console.error("Error deleting contact", error);
}
};
const handleEdit = () => {
setIsEditing(true);
};
const handleSave = async (updatedContact) => {
try {
if (selectedContact) {
await axios.put(`http://your-yii2-app-url/api/contact/${selectedContact.id}`, updatedContact);
} else {
await axios.post('http://your-yii2-app-url/api/contact', updatedContact);
}
setIsEditing(false);
fetchContacts();
setSelectedContact(null);
} catch (error) {
console.error("Error saving contact", error);
}
};
return (
<div>
<h1>Contact List</h1>
<table>
<thead>
<tr>
<th>Select</th>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{contacts.map(contact => (
<tr key={contact.id}>
<td>
<input type="radio" name="selectedContact" onChange={() => setSelectedContact(contact)} />
</td>
<td>{contact.id}</td>
<td>{contact.name}</td>
<td>{contact.email}</td>
<td>
<button onClick={() => setSelectedContact(contact)}>View</button>
<button onClick={() => { setSelectedContact(contact); setIsEditing(true); }}>Edit</button>
<button onClick={() => handleDelete(contact.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
{isEditing && (
<ContactForm
contact={selectedContact}
onSave={handleSave}
onCancel={() => setIsEditing(false)}
/>
)}
{!isEditing && selectedContact && (
<ContactDetail
contact={selectedContact}
onEdit={() => { setIsEditing(true); }}
onDelete={handleDelete}
/>
)}
</div>
);
};
export default ContactGridView;
Explanation
-
ContactForm Component: This component is reused for both creating and editing contacts. It uses props to determine if it is in edit mode and pre-fills the form with existing contact data when editing.
-
ContactDetail Component: This component displays detailed information about a selected contact, including options to edit or delete.
-
Radio Button Selection: The grid allows selecting a contact via a radio button. When a user selects a contact, the detail view is automatically updated.
-
Buttons for Viewing and Editing: Each row in the contact list includes buttons to view and edit contact details. The "Edit" button sets the state to allow editing.
-
Conditional Rendering: The state checks (isEditing and selectedContact) determine which component to display (the contact form for editing or the contact detail view).
Summary
This design provides a user-friendly interface for managing contacts in your application. The create/edit functionality is consolidated into a single form, while the detail view provides an overview of the selected contact. As your application grows, you could further enhance these components with better styling, validation, and error handling.