📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Axios is a promise-based HTTP client for the browser and Node.js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations.
Read more about Axios library at https://github.com/axios/axios
Features of Axios Library
- Make XMLHttpRequests from the browser
- Make HTTP requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Automatic transforms for JSON data
- Client-side support for protecting against XSRF
Installing Axios Library
$ npm install axios
$ bower install axios
$ yarn add axios
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Axios Important Methods
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
Backend Application using Spring Boot
The CRUD Restful web services at Spring boot CRUD with MySQL
Build React JS CRUD Application
I suggest you to watch a YouTube video tutorial series to understand more about this full-stack app at ReactJS + Spring Boot CRUD Full Stack Application
- Axios
- Fetch
- Superagent
- React-axios
- Use-HTTP
- React-request
1 - Create a React UI with Create React App
Using npx
npx create-react-app react-frontend
Using npm
npm init react-app react-frontend
Using Yarn
yarn create react-app react-frontend
3 - Adding Bootstrap in React Using NPM
$ npm install bootstrap --save
import 'bootstrap/dist/css/bootstrap.min.css';
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
4 - EmployeeService - Consume CRUD REST API Call
$ npm install --save axios
EmployeeService.js
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()
export default new EmployeeService();
Understand more about EmployeeService at ReactJS + Spring Boot CRUD Full Stack Application
5 - package.json
{
"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"
]
}
}
6 - React List Employee Component
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/_add');
}
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
componentDidMount(){
EmployeeService.getEmployees().then((res) => {
this.setState({ employees: res.data});
});
}
<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>
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)});
});
}
editEmployee(id){
this.props.history.push(`/add-employee/${id}`);
}
viewEmployee(id){
this.props.history.push(`/view-employee/${id}`);
}
addEmployee(){
this.props.history.push('/add-employee/_add');
}
Understand more about ListEmployeeComponent at ReactJS + Spring Boot CRUD Full Stack App - 8 - Creating React List Employee Component
7 - Create Header and Footer
7.1 HeaderComponent
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
7.2 FooterComponent
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
Understand more about creating Header and Footer in React app at ReactJS + Spring Boot CRUD Full Stack App - 10 - Add Header and Footer to React App
8 - Configure React App Routing
npm install react-router-dom
import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
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;
Understand more above routing configuration at ReactJS + Spring Boot CRUD Full Stack App - 11 - Configure Routing
9 - Add and Update Employee Component
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 === '_add'){
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 === '_add'){
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 === '_add'){
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
this.props.match.params.id
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);
}
componentDidMount(){
// step 4
if(this.state.id === '_add'){
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 === '_add'){
EmployeeService.createEmployee(employee).then(res =>{
this.props.history.push('/employees');
});
}else{
EmployeeService.updateEmployee(employee, this.state.id).then( res => {
this.props.history.push('/employees');
});
}
}
getTitle(){
if(this.state.id === '_add'){
return <h3 className="text-center">Add Employee</h3>
}else{
return <h3 className="text-center">Update Employee</h3>
}
}
cancel(){
this.props.history.push('/employees');
}
Understand more about CreateEmployeeConponent at ReactJS + Spring Boot CRUD Full Stack App - 13 - Creating React Add Employee Component.
10 - View Employee Component
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
Understand more about ViewEmployeeConponent at ReactJS + Spring Boot CRUD Full Stack App - 13 - Creating React Add Employee Component.
11 - Run React App
npm start
yarn start
12 - Demo of Full-Stack App
Source code on GitHub
https://github.com/RameshMF/ReactJS-Spring-Boot-CRUD-Full-Stack-App
Conclusion
Check out the complete tutorial at https://www.javaguides.net/2020/07/spring-boot-react-js-crud-example-tutorial.html
Comments
Post a Comment
Leave Comment