ENHANCING MERN STACK APPLICATIONS WITH MUI COMPONENTS : A BEGINNER’s PRACTICAL GUIDE
Introduction :
The MERN Stack is a popular technology stack for building full stack web applications. It includes React.js,Express.js and Node.js. React.js handles the FrontEnd, Node.js manages the backend, and MongoDB stores the data. While MERN provides a strong foundation, creating attractive and user-friendly interfaces requires UI Components. This is where MUI (Material -UI) comes in. MUI is a React Component Library that follows Google’s Material Design guideliness, offering prebuilt, customizable, and responsive UI components.
Why We Use MUI in MERN Stack Applications?
- PreBuilt Components : Save Development time by using ready- made buttons, forms, tables and dialogs.
- Responsive Design : Components adjust automatically across devices.
- Customizable Themes : Easily change colors, typography, and spacing.
- Better User Experience : MUI ensures a polished and modern UI without designing from scratch.
Setting Up a MERN + MUI Applications
Initialize MERN Project:
BackEnd SetUp:
mkdir mern-mui-app
cd mern-mui-app
mkdir server client
cd server
npm init -y
npm install express mongoose cors dotenv
Server/Index.js:
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));
app.get('/', (req, res) => {
res.send("Server is running");
});
app.listen(5000, () => console.log("Server started on port 5000"));
SetUp React FrontEnd with MUI:
FrontEnd SetUp:
npx create-react-app client
cd client
npm install @mui/material @mui/icons-material @emotion/react @emotion/styled axios
Creating a Simple MUI Form:
We’ll create a User Registration Form Using TextField, Button and Stack componentsfrom MUI.
import React, { useState } from 'react';
import { TextField, Button, Stack } from '@mui/material';
import axios from 'axios';
const RegisterForm = () => {
const [formData, setFormData] = useState({ name: '', email: '' });
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const res = await axios.post('http://localhost:5000/register', formData);
console.log('User Registered:', res.data);
} catch (err) {
console.error(err);
}
};
return (
<form onSubmit={handleSubmit}>
<Stack spacing={2} width={400} margin="auto" mt={5}>
<TextField
label="Name"
name="name"
value={formData.name}
onChange={handleChange}
variant="outlined"
required
/>
<TextField
label="Email"
name="email"
value={formData.email}
onChange={handleChange}
variant="outlined"
required
/>
<Button type="submit" variant="contained" color="primary">
Register
</Button>
</Stack>
</form>
);
};
export default RegisterForm;
Using MUI Table to Display Data:
We can fetch users from the Backend and display them in a DataGrid.
import React, { useEffect, useState } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import axios from 'axios';
const UserTable = () => {
const [users, setUsers] = useState([]);
useEffect(() => {
const fetchUsers = async () => {
const res = await axios.get('http://localhost:5000/users');
setUsers(res.data);
};
fetchUsers();
}, []);
const columns = [
{ field: '_id', headerName: 'ID', width: 220 },
{ field: 'name', headerName: 'Name', width: 150 },
{ field: 'email', headerName: 'Email', width: 200 }
];
return (
<div style={{ height: 400, width: '100%', marginTop: 20 }}>
<DataGrid rows={users} columns={columns} getRowId={(row) => row._id} />
</div>
);
};
export default UserTable;
Integrating Form and Table in App.js:
import React from 'react';
import RegisterForm from './components/RegisterForm';
import UserTable from './components/UserTable';
function App() {
return (
<div>
<h1 style={{ textAlign: 'center', marginTop: '20px' }}>MERN + MUI Example</h1>
<RegisterForm />
<UserTable />
</div>
);
}
export default App;
Key Takeaways:
- MUI Simplifies UI Development : PreBuilt component save development time.
- Responsive and mordern design : MUI Components looks professional and they were out of the box.
- Full MERN Stack Integration : MUI works seamlessly with React for FrontEnd interactions and BackEnd APIs.
- Scalability : Easily extend the UI with advanced components like dialogs, tables and modals.
By combining MERN and MUI, we can quickly build scalable Full-Stack Applications with Professional looking interfaces without spending weels on FrontEnd Design.