In React, The traditional MVC architecture is not strictly followed due to the component-based nature of React. But we can design the project as MVC architecture.
Here we have taken the below js file.
- Model (EmployeeModel.js): In this file, we contain data.
- View (EmployeeView.js): This is the view page. Which displays in the browser.
- Controller (EmployeeController.js): Acts as an intermediary between the view and the model, handling user inputs from the view, updating the model, and making API calls.
Here we have implemented this:
EmployeeModel.js
class EmployeeModel {
constructor() {
this.employeeId = '';
this.employeeName = '';
}
// Setter methods
setEmployeeId(employeeId) {
this.employeeId = employeeId;
}
setEmployeeName(employeeName) {
this.employeeName = employeeName;
}
// Getter methods
getEmployeeData() {
return {
employeeId: this.employeeId,
employeeName: this.employeeName
};
}
}
export default EmployeeModel;
EmployeeView.js
import React, { useState } from 'react';
import EmployeeController from './EmployeeController';
const EmployeeView = () => {
const [employeeId, setEmployeeId] = useState('');
const [employeeName, setEmployeeName] = useState('');
const controller = new EmployeeController();
const handleSubmit = () => {
controller.saveEmployeeData(employeeId, employeeName);
};
return (
<div>
<h1>Employee Details</h1>
<form onSubmit={handleSubmit}>
<label>
Employee ID:
<input type="text" value={employeeId} onChange={(e) => setEmployeeId(e.target.value)} />
</label>
<br />
<label>
Employee Name:
<input type="text" value={employeeName} onChange={(e) => setEmployeeName(e.target.value)} />
</label>
<br />
<button type="submit">Save</button>
</form>
</div>
);
};
export default EmployeeView;
EmployeeController.js
import EmployeeModel from './EmployeeModel';
class EmployeeController {
constructor() {
this.employeeModel = new EmployeeModel();
}
saveEmployeeData(employeeId, employeeName) {
this.employeeModel.setEmployeeId(employeeId);
this.employeeModel.setEmployeeName(employeeName);
const employeeData = this.employeeModel.getEmployeeData();
// Convert employeeData to JSON
const jsonData = JSON.stringify(employeeData);
// Example using Axios:
axios.post('http://your-api-endpoint.com/saveEmployeeData', jsonData, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
console.log('Employee data saved successfully:', response.data);
})
.catch(error => {
console.error('Error saving employee data:', error);
});
}
}
export default EmployeeController;
Done. Check in the browser...😊
0 Comments