Creating a well-organized file structure is crucial for maintaining scalability and readability in your ReactJS application. Below is a recommended file structure for your contact management frontend using ReactJS and Material UI (MUI). This structure separates concerns, making it easier to manage components, styles, and utilities.
Recommended File Structure
my-contact-app/
├── public/
│ ├── index.html
│ └── favicon.ico
├── src/
│ ├── assets/
│ │ └── images/
│ ├── components/
│ │ ├── ContactForm/
│ │ │ ├── ContactForm.jsx
│ │ │ └── ContactForm.css
│ │ ├── ContactsTable/
│ │ │ ├── ContactsTable.jsx
│ │ │ └── ContactsTable.css
│ │ ├── Layout/
│ │ │ ├── Header.jsx
│ │ │ ├── Footer.jsx
│ │ │ └── Layout.jsx
│ │ └── common/
│ │ ├── Button.jsx
│ │ └── TextField.jsx
│ ├── contexts/
│ │ └── ContactsContext.jsx
│ ├── hooks/
│ │ └── useContacts.js
│ ├── pages/
│ │ ├── Home.jsx
│ │ └── ContactDetails.jsx
│ ├── services/
│ │ └── api.js
│ ├── utils/
│ │ ├── validators.js
│ │ └── constants.js
│ ├── App.jsx
│ ├── index.js
│ └── theme.js
├── .gitignore
├── package.json
├── README.md
└── yarn.lock / package-lock.json
Directory Breakdown
Implementation Overview
1. Setting Up the Project
Use Create React App to bootstrap your project:
npx create-react-app my-contact-app
cd my-contact-app
Install Material UI and other dependencies:
npm install @mui/material @emotion/react @emotion/styled @mui/icons-material
2. Creating the Contact Form Component
src/components/ContactForm/ContactForm.jsx
import React, { useState } from 'react';
import { TextField, Button, Grid, Paper, Typography } from '@mui/material';
const ContactForm = ({ onSubmit }) => {
const [contact, setContact] = useState({
firstName: '',
lastName: '',
email: '',
phoneNumber: '',
company: '',
jobTitle: '',
});
const handleChange = (e) => {
setContact({ ...contact, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
onSubmit(contact);
setContact({
firstName: '',
lastName: '',
email: '',
phoneNumber: '',
company: '',
jobTitle: '',
});
};
return (
<Paper elevation={3} sx={{ padding: 4, marginBottom: 4 }}>
<Typography variant="h6" gutterBottom>
Add New Contact
</Typography>
<form onSubmit={handleSubmit}>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<TextField
label="First Name"
name="firstName"
value={contact.firstName}
onChange={handleChange}
fullWidth
required
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
label="Last Name"
name="lastName"
value={contact.lastName}
onChange={handleChange}
fullWidth
required
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
label="Email"
name="email"
type="email"
value={contact.email}
onChange={handleChange}
fullWidth
required
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
label="Phone Number"
name="phoneNumber"
type="tel"
value={contact.phoneNumber}
onChange={handleChange}
fullWidth
required
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
label="Company"
name="company"
value={contact.company}
onChange={handleChange}
fullWidth
/>
</Grid>
<Grid item xs={12} sm={6}>
<TextField
label="Job Title"
name="jobTitle"
value={contact.jobTitle}
onChange={handleChange}
fullWidth
/>
</Grid>
<Grid item xs={12}>
<Button type="submit" variant="contained" color="primary">
Add Contact
</Button>
</Grid>
</Grid>
</form>
</Paper>
);
};
export default ContactForm;
3. Creating the Contacts Table Component
src/components/ContactsTable/ContactsTable.jsx
import React, { useState } from 'react';
import {
Table, TableBody, TableCell, TableContainer,
TableHead, TableRow, Paper, IconButton,
TablePagination, TableSortLabel
} from '@mui/material';
import { Edit, Delete } from '@mui/icons-material';
const ContactsTable = ({ contacts, onEdit, onDelete }) => {
const [order, setOrder] = useState('asc');
const [orderBy, setOrderBy] = useState('firstName');
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(5);
const handleSortRequest = (property) => {
const isAsc = orderBy === property && order === 'asc';
setOrder(isAsc ? 'desc' : 'asc');
setOrderBy(property);
};
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const sortedContacts = contacts.sort((a, b) => {
if (a[orderBy] < b[orderBy]) return order === 'asc' ? -1 : 1;
if (a[orderBy] > b[orderBy]) return order === 'asc' ? 1 : -1;
return 0;
});
const displayedContacts = sortedContacts.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage);
return (
<Paper elevation={3}>
<TableContainer>
<Table>
<TableHead>
<TableRow>
{['firstName', 'lastName', 'email', 'phoneNumber', 'company', 'jobTitle'].map((headCell) => (
<TableCell key={headCell}>
<TableSortLabel
active={orderBy === headCell}
direction={orderBy === headCell ? order : 'asc'}
onClick={() => handleSortRequest(headCell)}
>
{headCell.charAt(0).toUpperCase() + headCell.slice(1)}
</TableSortLabel>
</TableCell>
))}
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{displayedContacts.map((contact) => (
<TableRow key={contact.id}>
<TableCell>{contact.firstName}</TableCell>
<TableCell>{contact.lastName}</TableCell>
<TableCell>{contact.email}</TableCell>
<TableCell>{contact.phoneNumber}</TableCell>
<TableCell>{contact.company}</TableCell>
<TableCell>{contact.jobTitle}</TableCell>
<TableCell>
<IconButton color="primary" onClick={() => onEdit(contact)}>
<Edit />
</IconButton>
<IconButton color="secondary" onClick={() => onDelete(contact.id)}>
<Delete />
</IconButton>
</TableCell>
</TableRow>
))}
{displayedContacts.length === 0 && (
<TableRow>
<TableCell colSpan={7} align="center">
No contacts found.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</TableContainer>
<TablePagination
component="div"
count={contacts.length}
page={page}
onPageChange={handleChangePage}
rowsPerPage={rowsPerPage}
onRowsPerPageChange={handleChangeRowsPerPage}
rowsPerPageOptions={[5, 10, 25]}
/>
</Paper>
);
};
export default ContactsTable;
4. Managing State with Context API
src/contexts/ContactsContext.jsx
import React, { createContext, useState } from 'react';
export const ContactsContext = createContext();
const ContactsProvider = ({ children }) => {
const [contacts, setContacts] = useState([]);
const addContact = (contact) => {
setContacts([...contacts, { ...contact, id: Date.now() }]);
};
const editContact = (updatedContact) => {
setContacts(contacts.map(contact => contact.id === updatedContact.id ? updatedContact : contact));
};
const deleteContact = (id) => {
setContacts(contacts.filter(contact => contact.id !== id));
};
return (
<ContactsContext.Provider value={{ contacts, addContact, editContact, deleteContact }}>
{children}
</ContactsContext.Provider>
);
};
export default ContactsProvider;
5. Assembling Everything in the Main App
src/App.jsx
import React, { useContext, useState } from 'react';
import { Container, Typography, Dialog, DialogTitle, DialogContent } from '@mui/material';
import ContactForm from './components/ContactForm/ContactForm';
import ContactsTable from './components/ContactsTable/ContactsTable';
import ContactsProvider, { ContactsContext } from './contexts/ContactsContext';
const AppContent = () => {
const { contacts, addContact, editContact, deleteContact } = useContext(ContactsContext);
const [editingContact, setEditingContact] = useState(null);
const handleEdit = (contact) => {
setEditingContact(contact);
};
const handleDelete = (id) => {
deleteContact(id);
};
const handleFormSubmit = (contact) => {
if (editingContact) {
editContact({ ...contact, id: editingContact.id });
setEditingContact(null);
} else {
addContact(contact);
}
};
const handleCloseDialog = () => {
setEditingContact(null);
};
return (
<Container maxWidth="md" sx={{ marginTop: 4 }}>
<Typography variant="h4" gutterBottom align="center">
Contact Management
</Typography>
<ContactForm onSubmit={handleFormSubmit} />
<ContactsTable contacts={contacts} onEdit={handleEdit} onDelete={handleDelete} />
<Dialog open={Boolean(editingContact)} onClose={handleCloseDialog}>
<DialogTitle>Edit Contact</DialogTitle>
<DialogContent>
{editingContact && (
<ContactForm
onSubmit={handleFormSubmit}
initialData={editingContact}
/>
)}
</DialogContent>
</Dialog>
</Container>
);
};
const App = () => (
<ContactsProvider>
<AppContent />
</ContactsProvider>
);
export default App;
6. Entry Point
src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
const theme = createTheme({
// Customize your theme here
palette: {
primary: {
main: '#1976d2',
},
secondary: {
main: '#dc004e',
},
},
});
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<ThemeProvider theme={theme}>
<CssBaseline />
<App />
</ThemeProvider>
);
Additional Tips
-
Routing: If your application grows, consider adding react-router-dom for handling multiple pages/routes.
npm install react-router-dom
Then, set up your routes in App.jsx or a separate Routes.jsx component.
-
Form Validation: Implement form validation using libraries like Formik and Yup for better user input handling.
-
API Integration: Replace the in-memory state with real API calls. Use axios or the native fetch API in src/services/api.js to communicate with your backend.
npm install axios
-
Responsive Design: Ensure your components are responsive. MUI's Grid system is helpful for this.
-
Error Handling: Implement proper error handling for API calls and user actions.
-
Testing: Set up testing with libraries like Jest and React Testing Library to ensure your components work as expected.
Conclusion
This file structure provides a scalable foundation for your contact management frontend application using ReactJS and Material UI. As your application grows, you can further modularize components, add more contexts or state management solutions like Redux, and integrate additional features seamlessly. Always keep your components reusable and your codebase organized to maintain efficiency and ease of maintenance.