Absolutely! I can help you develop the frontend for your contact management application using ReactJS and Material UI (MUI). Below, you'll find a comprehensive guide that includes setting up the project, installing necessary dependencies, and creating the required components with example code snippets.
Table of Contents
- Project Setup
- Installing Dependencies
- Project Structure
- Creating the Contact Form
- Creating the Contacts Table
- Integrating API Calls
- Putting It All Together
- Running the Application
- Additional Enhancements
1. Project Setup
First, let's set up a new React project using Create React App.
npx create-react-app contact-manager
cd contact-manager
2. Installing Dependencies
Install the necessary dependencies: Material UI (MUI) components, Axios for HTTP requests, and any other utilities you might need.
npm install @mui/material @emotion/react @emotion/styled @mui/icons-material axios
@mui/material: Core Material UI components.
@mui/icons-material: Material UI icons.
@emotion/react and @emotion/styled: Required peer dependencies for MUI.
axios: For making HTTP requests to the backend API.
3. Project Structure
Organize your project for better scalability and maintainability. Here's a suggested structure:
src/
│
├── components/
│ ├── ContactForm.jsx
│ └── ContactsTable.jsx
│
├── services/
│ └── api.js
│
├── App.js
├── index.js
└── ... other files
4. Creating the Contact Form
Create a form to capture new contact information using MUI components.
src/components/ContactForm.jsx
import React, { useState } from 'react';
import { TextField, Button, Box, Typography, Grid } from '@mui/material';
import axios from 'axios';
const ContactForm = ({ onContactAdded }) => {
const [formData, setFormData] = useState({
first_name: '',
last_name: '',
email: '',
phone_number: '',
company: '',
job_title: '',
});
const [errors, setErrors] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const validate = () => {
let temp = {};
temp.first_name = formData.first_name ? '' : 'First Name is required.';
temp.last_name = formData.last_name ? '' : 'Last Name is required.';
temp.email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email) ? '' : 'Email is not valid.';
temp.phone_number = formData.phone_number ? '' : 'Phone Number is required.';
setErrors({ ...temp });
return Object.values(temp).every((x) => x === '');
};
const handleSubmit = async (e) => {
e.preventDefault();
if (validate()) {
try {
const response = await axios.post('/api/contacts', formData);
onContactAdded(response.data);
setFormData({
first_name: '',
last_name: '',
email: '',
phone_number: '',
company: '',
job_title: '',
});
} catch (error) {
console.error('Error adding contact:', error);
}
}
};
return (
<Box sx={{ mt: 4, mb: 4 }}>
<Typography variant="h6" gutterBottom>
Add New Contact
</Typography>
<form onSubmit={handleSubmit}>
<Grid container spacing={2}>
{/* First Name */}
<Grid item xs={12} sm={6}>
<TextField
name="first_name"
label="First Name"
variant="outlined"
fullWidth
value={formData.first_name}
onChange={handleChange}
error={Boolean(errors.first_name)}
helperText={errors.first_name}
/>
</Grid>
{/* Last Name */}
<Grid item xs={12} sm={6}>
<TextField
name="last_name"
label="Last Name"
variant="outlined"
fullWidth
value={formData.last_name}
onChange={handleChange}
error={Boolean(errors.last_name)}
helperText={errors.last_name}
/>
</Grid>
{/* Email */}
<Grid item xs={12} sm={6}>
<TextField
name="email"
label="Email"
variant="outlined"
fullWidth
value={formData.email}
onChange={handleChange}
error={Boolean(errors.email)}
helperText={errors.email}
/>
</Grid>
{/* Phone Number */}
<Grid item xs={12} sm={6}>
<TextField
name="phone_number"
label="Phone Number"
variant="outlined"
fullWidth
value={formData.phone_number}
onChange={handleChange}
error={Boolean(errors.phone_number)}
helperText={errors.phone_number}
/>
</Grid>
{/* Company */}
<Grid item xs={12} sm={6}>
<TextField
name="company"
label="Company"
variant="outlined"
fullWidth
value={formData.company}
onChange={handleChange}
/>
</Grid>
{/* Job Title */}
<Grid item xs={12} sm={6}>
<TextField
name="job_title"
label="Job Title"
variant="outlined"
fullWidth
value={formData.job_title}
onChange={handleChange}
/>
</Grid>
{/* Submit Button */}
<Grid item xs={12}>
<Button type="submit" variant="contained" color="primary">
Add Contact
</Button>
</Grid>
</Grid>
</form>
</Box>
);
};
export default ContactForm;
Explanation:
- Form State Management: The component uses React's
useState hook to manage form data and validation errors.
- Validation: A simple validation function checks for required fields and a valid email format.
- Submission: On form submission, it sends a POST request to
/api/contacts and invokes a callback onContactAdded to update the contacts list in the parent component.
- Material UI Components: Uses
TextField, Button, Box, Typography, and Grid for layout and styling.
5. Creating the Contacts Table
Create a table to display all contacts with pagination, sorting, and action buttons for editing and deleting.
src/components/ContactsTable.jsx
import React, { useState, useEffect } from 'react';
import {
Table, TableBody, TableCell, TableContainer, TableHead, TableRow,
Paper, IconButton, TablePagination, TableSortLabel, Dialog, DialogTitle,
DialogContent, DialogActions, Button, TextField, Box, Typography
} from '@mui/material';
import { Edit, Delete } from '@mui/icons-material';
import axios from 'axios';
const ContactsTable = () => {
const [contacts, setContacts] = useState([]);
const [order, setOrder] = useState('asc');
const [orderBy, setOrderBy] = useState('first_name');
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(5);
// For Editing
const [openEdit, setOpenEdit] = useState(false);
const [currentContact, setCurrentContact] = useState(null);
const [editData, setEditData] = useState({});
useEffect(() => {
fetchContacts();
}, []);
const fetchContacts = async () => {
try {
const response = await axios.get('/api/contacts');
setContacts(response.data);
} catch (error) {
console.error('Error fetching contacts:', error);
}
};
const handleRequestSort = (property) => {
const isAsc = orderBy === property && order === 'asc';
setOrder(isAsc ? 'desc' : 'asc');
setOrderBy(property);
};
const sortedContacts = () => {
return contacts.sort((a, b) => {
if (order === 'asc') {
return a[orderBy].localeCompare(b[orderBy]);
}
return b[orderBy].localeCompare(a[orderBy]);
});
};
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
// Delete Contact
const handleDelete = async (id) => {
if (window.confirm('Are you sure you want to delete this contact?')) {
try {
await axios.delete(`/api/contacts/${id}`);
setContacts(contacts.filter(contact => contact.id !== id));
} catch (error) {
console.error('Error deleting contact:', error);
}
}
};
// Edit Contact
const handleEditOpen = (contact) => {
setCurrentContact(contact);
setEditData(contact);
setOpenEdit(true);
};
const handleEditClose = () => {
setOpenEdit(false);
setCurrentContact(null);
setEditData({});
};
const handleEditChange = (e) => {
const { name, value } = e.target;
setEditData({ ...editData, [name]: value });
};
const handleEditSubmit = async () => {
try {
const response = await axios.put(`/api/contacts/${currentContact.id}`, editData);
setContacts(contacts.map(contact => contact.id === currentContact.id ? response.data : contact));
handleEditClose();
} catch (error) {
console.error('Error updating contact:', error);
}
};
return (
<Box>
<Typography variant="h6" gutterBottom>
Contacts
</Typography>
<TableContainer component={Paper}>
<Table aria-label="contacts table">
<TableHead>
<TableRow>
{/* Define Table Headers with Sort */}
{['first_name', 'last_name', 'email', 'phone_number', 'company', 'job_title'].map((headCell) => (
<TableCell key={headCell}>
<TableSortLabel
active={orderBy === headCell}
direction={orderBy === headCell ? order : 'asc'}
onClick={() => handleRequestSort(headCell)}
>
{headCell.replace('_', ' ').toUpperCase()}
</TableSortLabel>
</TableCell>
))}
<TableCell>ACTIONS</TableCell>
</TableRow>
</TableHead>
<TableBody>
{sortedContacts()
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((contact) => (
<TableRow key={contact.id}>
<TableCell>{contact.first_name}</TableCell>
<TableCell>{contact.last_name}</TableCell>
<TableCell>{contact.email}</TableCell>
<TableCell>{contact.phone_number}</TableCell>
<TableCell>{contact.company}</TableCell>
<TableCell>{contact.job_title}</TableCell>
<TableCell>
<IconButton color="primary" onClick={() => handleEditOpen(contact)}>
<Edit />
</IconButton>
<IconButton color="secondary" onClick={() => handleDelete(contact.id)}>
<Delete />
</IconButton>
</TableCell>
</TableRow>
))}
{contacts.length === 0 && (
<TableRow>
<TableCell colSpan={7} align="center">
No contacts found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
{/* Pagination */}
<TablePagination
component="div"
count={contacts.length}
page={page}
onPageChange={handleChangePage}
rowsPerPage={rowsPerPage}
onRowsPerPageChange={handleChangeRowsPerPage}
rowsPerPageOptions={[5, 10, 25]}
/>
</TableContainer>
{/* Edit Dialog */}
<Dialog open={openEdit} onClose={handleEditClose}>
<DialogTitle>Edit Contact</DialogTitle>
<DialogContent>
<Box component="form" sx={{ mt: 2 }}>
<Grid container spacing={2}>
{/* First Name */}
<Grid item xs={12} sm={6}>
<TextField
name="first_name"
label="First Name"
variant="outlined"
fullWidth
value={editData.first_name || ''}
onChange={handleEditChange}
/>
</Grid>
{/* Last Name */}
<Grid item xs={12} sm={6}>
<TextField
name="last_name"
label="Last Name"
variant="outlined"
fullWidth
value={editData.last_name || ''}
onChange={handleEditChange}
/>
</Grid>
{/* Email */}
<Grid item xs={12} sm={6}>
<TextField
name="email"
label="Email"
variant="outlined"
fullWidth
value={editData.email || ''}
onChange={handleEditChange}
/>
</Grid>
{/* Phone Number */}
<Grid item xs={12} sm={6}>
<TextField
name="phone_number"
label="Phone Number"
variant="outlined"
fullWidth
value={editData.phone_number || ''}
onChange={handleEditChange}
/>
</Grid>
{/* Company */}
<Grid item xs={12} sm={6}>
<TextField
name="company"
label="Company"
variant="outlined"
fullWidth
value={editData.company || ''}
onChange={handleEditChange}
/>
</Grid>
{/* Job Title */}
<Grid item xs={12} sm={6}>
<TextField
name="job_title"
label="Job Title"
variant="outlined"
fullWidth
value={editData.job_title || ''}
onChange={handleEditChange}
/>
</Grid>
</Grid>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={handleEditClose} color="secondary">
Cancel
</Button>
<Button onClick={handleEditSubmit} variant="contained" color="primary">
Save
</Button>
</DialogActions>
</Dialog>
</Box>
);
};
export default ContactsTable;
Explanation:
- Data Fetching: Uses Axios to fetch contacts from
/api/contacts on component mount.
- Sorting: Implements sorting functionality based on table headers using
TableSortLabel.
- Pagination: Utilizes
TablePagination for pagination controls.
- Editing: Includes a dialog with a form to edit contact details. On submission, sends a PUT request to update the contact.
- Deleting: Provides a delete button that sends a DELETE request to remove the contact.
- Material UI Components: Uses
Table, TableBody, TableCell, TableContainer, TableHead, TableRow, IconButton, Dialog, etc., for layout and interactions.
6. Integrating API Calls
To manage API endpoints more efficiently, create a dedicated service file.
src/services/api.js
import axios from 'axios';
const api = axios.create({
baseURL: 'http://localhost:8000', // Replace with your backend URL
headers: {
'Content-Type': 'application/json',
},
});
export default api;
Note: Adjust the baseURL to match your backend server's address. If your frontend and backend are on the same domain and port, you might not need to set it explicitly. Also, ensure that your backend allows Cross-Origin requests if they are on different domains or ports.
Update Components to Use the Service:
Modify ContactForm.jsx and ContactsTable.jsx to use the api instance instead of directly using axios.
For example, in ContactForm.jsx:
import api from '../services/api';
// Replace axios.post with api.post
const response = await api.post('/api/contacts', formData);
Similarly, in ContactsTable.jsx:
import api from '../services/api';
// Replace axios.get, axios.delete, axios.put with api.get, etc.
const response = await api.get('/api/contacts');
// and so on...
7. Putting It All Together
Now, integrate both ContactForm and ContactsTable into your main App component.
src/App.js
import React, { useState } from 'react';
import { Container, Typography } from '@mui/material';
import ContactForm from './components/ContactForm';
import ContactsTable from './components/ContactsTable';
function App() {
// To trigger re-fetching or updating contacts, you can manage state here
const [refresh, setRefresh] = useState(false);
const handleContactAdded = () => {
// Toggle refresh to trigger re-fetch in ContactsTable
setRefresh(!refresh);
};
return (
<Container maxWidth="md">
<Typography variant="h4" align="center" gutterBottom sx={{ mt: 4 }}>
Contact Manager
</Typography>
<ContactForm onContactAdded={handleContactAdded} />
<ContactsTable key={refresh} />
</Container>
);
}
export default App;
Explanation:
- State Management: The
App component maintains a refresh state to trigger re-rendering of the ContactsTable when a new contact is added.
- Components Integration: It renders
ContactForm and ContactsTable inside a Container for proper spacing and alignment.
8. Running the Application
Starting the React Application
Ensure your Django backend is running and accessible.
In the contact-manager directory, start the React app:
npm start
The app should be accessible at http://localhost:3000 by default.
Handling CORS (If Necessary)
If your React frontend and Django backend are on different origins (e.g., different ports), you may encounter CORS issues. To resolve this, ensure you have CORS headers properly set up in your Django backend.
In Django:
- Install
django-cors-headers:
pip install django-cors-headers
- Add to
INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
...
'corsheaders',
...
]
- Add middleware in
settings.py:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
- Configure allowed origins in
settings.py:
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]
Note: Adjust the allowed origins as per your deployment setup.
9. Additional Enhancements
Here are a few suggestions to further improve your application:
- Form Validation: Enhance validation using libraries like
formik and yup for more robust form handling.
- Notifications: Implement user feedback using
Snackbar for success and error messages.
- Search Functionality: Add a search bar to filter contacts based on different attributes.
- Responsive Design: Ensure the UI is responsive across different devices.
- State Management: For larger applications, consider using state management libraries like Redux.
This should give you a solid foundation for your frontend contact management application using ReactJS and Material UI. Feel free to customize and extend the functionality as per your requirements. If you encounter any issues or have further questions, don't hesitate to ask!