-
Notifications
You must be signed in to change notification settings - Fork 603
Spring boot React JS CRUD Example Tutorial Part 2 Front End React App
This file contains all the required dependencies for our React JS project. Most importantly, u can check the current version of React that you are using. It has all the scripts to start, build, and eject our React app.
{
"name": "react-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"bootstrap": "^4.5.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
import axios from 'axios';
const EMPLOYEE_API_BASE_URL = "http://localhost:8080/api/v1/employees";
class EmployeeService {
getEmployees(){
return axios.get(EMPLOYEE_API_BASE_URL);
}
createEmployee(employee){
return axios.post(EMPLOYEE_API_BASE_URL, employee);
}
getEmployeeById(employeeId){
return axios.get(EMPLOYEE_API_BASE_URL + '/' + employeeId);
}
updateEmployee(employee, employeeId){
return axios.put(EMPLOYEE_API_BASE_URL + '/' + employeeId, employee);
}
deleteEmployee(employeeId){
return axios.delete(EMPLOYEE_API_BASE_URL + '/' + employeeId);
}
}
export default new EmployeeService()
In this section, we will create a new folder called components inside src folder. Then create a new file called ListUserComponent.jsx. Within this file create a React class component named ListUserComponent with following content:
import React, { Component } from 'react'
import EmployeeService from '../services/EmployeeService'
class ListEmployeeComponent extends Component {
constructor(props) {
super(props)
this.state = {
employees: []
}
this.addEmployee = this.addEmployee.bind(this);
this.editEmployee = this.editEmployee.bind(this);
this.deleteEmployee = this.deleteEmployee.bind(this);
}
deleteEmployee(id){
EmployeeService.deleteEmployee(id).then( res => {
this.setState({employees: this.state.employees.filter(employee => employee.id !== id)});
});
}
viewEmployee(id){
this.props.history.push(`/view-employee/${id}`);
}
editEmployee(id){
this.props.history.push(`/add-employee/${id}`);
}
componentDidMount(){
EmployeeService.getEmployees().then((res) => {
this.setState({ employees: res.data});
});
}
addEmployee(){
this.props.history.push('/add-employee/-1');
}
render() {
return (
<div>
<h2 className="text-center">Employees List</h2>
<div className = "row">
<button className="btn btn-primary" onClick={this.addEmployee}> Add Employee</button>
</div>
<br></br>
<div className = "row">
<table className = "table table-striped table-bordered">
<thead>
<tr>
<th> Employee First Name</th>
<th> Employee Last Name</th>
<th> Employee Email Id</th>
<th> Actions</th>
</tr>
</thead>
<tbody>
{
this.state.employees.map(
employee =>
<tr key = {employee.id}>
<td> { employee.firstName} </td>
<td> {employee.lastName}</td>
<td> {employee.emailId}</td>
<td>
<button onClick={ () => this.editEmployee(employee.id)} className="btn btn-info">Update </button>
<button style={{marginLeft: "10px"}} onClick={ () => this.deleteEmployee(employee.id)} className="btn btn-danger">Delete </button>
<button style={{marginLeft: "10px"}} onClick={ () => this.viewEmployee(employee.id)} className="btn btn-info">View </button>
</td>
</tr>
)
}
</tbody>
</table>
</div>
</div>
)
}
}
export default ListEmployeeComponent
Let's understand the above code.
The componentDidMount() is executed when the component is mounted for the first time. In the implementation, it actually invokes the service class method to fetch the employees from an API call and populates the state variable employees. When there is a change in the state, React Js reacts and updates the UI:
componentDidMount(){
EmployeeService.getEmployees().then((res) => {
this.setState({ employees: res.data});
});
}
We are using the ES6 feature that is map operator to loop over our employees list and create the view:
<tbody>
{
this.state.employees.map(
employee =>
<tr key = {employee.id}>
<td> { employee.firstName} </td>
<td> {employee.lastName}</td>
<td> {employee.emailId}</td>
<td>
<button onClick={ () => this.editEmployee(employee.id)} className="btn btn-info">Update </button>
<button style={{marginLeft: "10px"}} onClick={ () => this.deleteEmployee(employee.id)} className="btn btn-danger">Delete </button>
<button style={{marginLeft: "10px"}} onClick={ () => this.viewEmployee(employee.id)} className="btn btn-info">View </button>
</td>
</tr>
)
}
</tbody>
The constructor() is invoked before the component is mounted. In the constructor, we have declared our state variables and bind the different methods so that they are accessible from the state inside of the render() method.
constructor(props) {
super(props)
this.state = {
employees: []
}
this.addEmployee = this.addEmployee.bind(this);
this.editEmployee = this.editEmployee.bind(this);
this.deleteEmployee = this.deleteEmployee.bind(this);
}
On the click of the delete button, we filter method of an array to filter out the deleted employee:
deleteEmployee(id){
EmployeeService.deleteEmployee(id).then( res => {
this.setState({employees: this.state.employees.filter(employee => employee.id !== id)});
});
}
On the click of the Update button, we will navigate to Update Employee page using following code:
editEmployee(id){
this.props.history.push(`/add-employee/${id}`);
}
On the click of the View button, we will navigate to View Employee page using the following code:
viewEmployee(id){
this.props.history.push(`/view-employee/${id}`);
}
On the click of the Add Employee button, we will navigate to Add Employee page using the following code:
addEmployee(){
this.props.history.push('/add-employee/-1');
}
Let's create a new file named HeaderComponent.js and within this file, create a component named HeaderComponent with following code:
import React, { Component } from 'react'
class HeaderComponent extends Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<div>
<header>
<nav className="navbar navbar-expand-md navbar-dark bg-dark">
<div><a href="https://javaguides.net" className="navbar-brand">Employee Management App</a></div>
</nav>
</header>
</div>
)
}
}
export default HeaderComponent
Let's create a new file named FooterComponent.js and within this file, create a component named FooterComponent with following code:
import React, { Component } from 'react'
class FooterComponent extends Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<div>
<footer className = "footer">
<span className="text-muted">All Rights Reserved 2020 @JavaGuides</span>
</footer>
</div>
)
}
}
export default FooterComponent
To use React Router, you first have to install it using NPM:
npm install react-router-dom
You'll need to import BrowserRouter, Route, and Switch from react-router-dom package:
import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
Let's open App component and configure routing. We use the Switch element (open and closing tags) these ensure that only one component is rendered at a time.
Replace App component with following code:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom'
import ListEmployeeComponent from './components/ListEmployeeComponent';
import HeaderComponent from './components/HeaderComponent';
import FooterComponent from './components/FooterComponent';
import CreateEmployeeComponent from './components/CreateEmployeeComponent';
import ViewEmployeeComponent from './components/ViewEmployeeComponent';
function App() {
return (
<div>
<Router>
<HeaderComponent />
<div className="container">
<Switch>
<Route path = "/" exact component = {ListEmployeeComponent}></Route>
<Route path = "/employees" component = {ListEmployeeComponent}></Route>
<Route path = "/add-employee/:id" component = {CreateEmployeeComponent}></Route>
<Route path = "/view-employee/:id" component = {ViewEmployeeComponent}></Route>
{/* <Route path = "/update-employee/:id" component = {UpdateEmployeeComponent}></Route> */}
</Switch>
</div>
<FooterComponent />
</Router>
</div>
);
}
export default App;
In this section, we will implement Add employee and update employee functionality. We will use the same React Component to perform both add and update employee operation.
Let's create a new file called CreateEmployeeComponent.jsx. Within this file create a React class component named CreateEmployeeComponent with following content:
import React, { Component } from 'react'
import EmployeeService from '../services/EmployeeService';
class CreateEmployeeComponent extends Component {
constructor(props) {
super(props)
this.state = {
// step 2
id: this.props.match.params.id,
firstName: '',
lastName: '',
emailId: ''
}
this.changeFirstNameHandler = this.changeFirstNameHandler.bind(this);
this.changeLastNameHandler = this.changeLastNameHandler.bind(this);
this.saveOrUpdateEmployee = this.saveOrUpdateEmployee.bind(this);
}
// step 3
componentDidMount(){
// step 4
if(this.state.id == -1){
return
}else{
EmployeeService.getEmployeeById(this.state.id).then( (res) =>{
let employee = res.data;
this.setState({firstName: employee.firstName,
lastName: employee.lastName,
emailId : employee.emailId
});
});
}
}
saveOrUpdateEmployee = (e) => {
e.preventDefault();
let employee = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
console.log('employee => ' + JSON.stringify(employee));
// step 5
if(this.state.id == -1){
EmployeeService.createEmployee(employee).then(res =>{
this.props.history.push('/employees');
});
}else{
EmployeeService.updateEmployee(employee, this.state.id).then( res => {
this.props.history.push('/employees');
});
}
}
changeFirstNameHandler= (event) => {
this.setState({firstName: event.target.value});
}
changeLastNameHandler= (event) => {
this.setState({lastName: event.target.value});
}
changeEmailHandler= (event) => {
this.setState({emailId: event.target.value});
}
cancel(){
this.props.history.push('/employees');
}
getTitle(){
if(this.state.id == -1){
return <h3 className="text-center">Add Employee</h3>
}else{
return <h3 className="text-center">Update Employee</h3>
}
}
render() {
return (
<div>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3">
{
this.getTitle()
}
<div className = "card-body">
<form>
<div className = "form-group">
<label> First Name: </label>
<input placeholder="First Name" name="firstName" className="form-control"
value={this.state.firstName} onChange={this.changeFirstNameHandler}/>
</div>
<div className = "form-group">
<label> Last Name: </label>
<input placeholder="Last Name" name="lastName" className="form-control"
value={this.state.lastName} onChange={this.changeLastNameHandler}/>
</div>
<div className = "form-group">
<label> Email Id: </label>
<input placeholder="Email Address" name="emailId" className="form-control"
value={this.state.emailId} onChange={this.changeEmailHandler}/>
</div>
<button className="btn btn-success" onClick={this.saveOrUpdateEmployee}>Save</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CreateEmployeeComponent
Let's understand the above code.
We retrieve employee id from the route using the following line of code:
this.props.match.params.id
In the constructor, we have declared our state variables and bind the different methods so that they are accessible from the state inside of the render() method.
constructor(props) {
super(props)
this.state = {
// step 2
id: this.props.match.params.id,
firstName: '',
lastName: '',
emailId: ''
}
this.changeFirstNameHandler = this.changeFirstNameHandler.bind(this);
this.changeLastNameHandler = this.changeLastNameHandler.bind(this);
this.saveOrUpdateEmployee = this.saveOrUpdateEmployee.bind(this);
}
The componentDidMount() is executed when the component is mounted for the first time. In componentDidMount() method, if id is -1 then we don't do anything else we retrieve employee by id using EmployeeService.getEmployeeById() method:
componentDidMount(){
// step 4
if(this.state.id == -1){
return
}else{
EmployeeService.getEmployeeById(this.state.id).then( (res) =>{
let employee = res.data;
this.setState({firstName: employee.firstName,
lastName: employee.lastName,
emailId : employee.emailId
});
});
}
}
In saveOrUpdateEmployee () method, we check if id is -1 then we call EmployeeService.createEmployee() method which internally make a REST API call to store employee data into MySQL database. If id is any positive number then we call EmployeeService.updateEmployee() method which internally make a REST API call to store updated employee data into MySQL database:
saveOrUpdateEmployee = (e) => {
e.preventDefault();
let employee = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
console.log('employee => ' + JSON.stringify(employee));
// step 5
if(this.state.id == -1){
EmployeeService.createEmployee(employee).then(res =>{
this.props.history.push('/employees');
});
}else{
EmployeeService.updateEmployee(employee, this.state.id).then( res => {
this.props.history.push('/employees');
});
}
}
We are using getTitle() method to get the title for Add and Employee page based on id:
getTitle(){
if(this.state.id == -1){
return <h3 className="text-center">Add Employee</h3>
}else{
return <h3 className="text-center">Update Employee</h3>
}
}
Onclick on Cancel button, the cancel() method called and it will navigate user to employees list page:
cancel(){
this.props.history.push('/employees');
}
import React, { Component } from 'react'
import EmployeeService from '../services/EmployeeService'
class ViewEmployeeComponent extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
employee: {}
}
}
componentDidMount(){
EmployeeService.getEmployeeById(this.state.id).then( res => {
this.setState({employee: res.data});
})
}
render() {
return (
<div>
<br></br>
<div className = "card col-md-6 offset-md-3">
<h3 className = "text-center"> View Employee Details</h3>
<div className = "card-body">
<div className = "row">
<label> Employee First Name: </label>
<div> { this.state.employee.firstName }</div>
</div>
<div className = "row">
<label> Employee Last Name: </label>
<div> { this.state.employee.lastName }</div>
</div>
<div className = "row">
<label> Employee Email ID: </label>
<div> { this.state.employee.emailId }</div>
</div>
</div>
</div>
</div>
)
}
}
export default ViewEmployeeComponent