📘 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.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Check out React JS Spring Boot REST API Tutorial at https://www.javaguides.net/2020/07/react-js-spring-boot-rest-api-example-tutorial.html
What we will build?
Prerequisites
You will need the following prerequisites to successfully complete the steps in this tutorial:
- JavaScript fundamentals
- Basic understanding of REST APIs
- Node and NPM installed on your machine
Making an Ajax Calls in React
- Axios
- Fetch
- Superagent
- React-axios
- Use-http
- React-request
Fetch API Overview
- The Fetch API is a web standard built into most modern browsers to let us make HTTP requests to the server.
- The most important part is that fetch is asynchronous so it will run in the background and let you know when it finishes using promises.
- The fetch API allows us to make HTTP requests with the standard HTTP verbs: GET, POST, PUT, PATCH, and DELETE.
- The fetch function returns a promise which resolves when the request completes.
Develop Spring Boot Backend Application
1. Create Spring Boot Project in Eclipse STS IDE
2. Add maven dependencies
<?xml version="1.0" encoding="UTF-8"?>
<project
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<groupId>net.javaguides</groupId>
<artifactId>springboot-reactjs-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-reactjs-example</name>
<description>Demo project for Spring Boot and React JS</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3. Create Simple REST API - /books
package net.javaguides.springboot;
import java.util.Arrays;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookController {
@CrossOrigin(origins = "http://localhost:3000")
@GetMapping("/books")
public List < Book > getBooks() {
return Arrays.asList(new Book(1, "Core Java"), new Book(2, "Effective Java"), new Book(3, "Head First Java"));
}
}
class Book {
private int id;
private String bookName;
public Book(int id, String bookName) {
super();
this.id = id;
this.bookName = bookName;
}
public int getId() {
return id;
}
public String getBookName() {
return bookName;
}
public void setId(int id) {
this.id = id;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
}
4. Run Spring Boot Application and Test Rest API
package net.javaguides.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootReactjsExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootReactjsExampleApplication.class, args);
}
}
Develop React JS Frontend Application
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
my-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
- public/index.html is the page template;
- src/index.js is the JavaScript entry point.
Let's quickly explore the project structure.
2. 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();
3. Fetching and Displaying the REST API
const BOOKS_REST_API = 'http://localhost:8080/books';
class APIService {
getBooks(){
return fetch(BOOKS_REST_API,{
method: 'get',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
'credentials': 'same-origin'
})
.then(res => res.json());
}
}
export default new APIService();
export default new APIService();
4. Develop a React Component
import React from 'react'
import APIService from '../service/APIService'
export default class BookComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
books: []
}
}
componentDidMount(){
APIService.getBooks().then((data) => {
this.setState({ books: data })
console.log(this.state.data)
})
.catch(function (ex) {
console.log('Response parsing failed. Error: ', ex);
});;
}
render() {
return (
<div>
<h2 className="text-center">Book Details</h2>
<table className="table table-striped">
<thead>
<tr>
<th>Book Id</th>
<th>Book Name</th>
<th>Book Author</th>
</tr>
</thead>
<tbody>
{
this.state.books.map(book =>
<tr key={book.id}>
<td>{book.id}</td>
<td>{book.bookName}</td>
<td>{book.author}</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}
}
- constructor() - The constructor() is invoked before the component is mounted. In the constructor, we have declared our book state variable:
constructor(props) {
super(props)
this.state = {
books: []
}
}
- componentDidMount() - The componentDidMount() is called as soon as the component is mounted and ready. This is a good place to initiate API calls if you need to load data from a remote endpoint. Note that we are calling the loadBooks() method of APIService from componentDidMount() method:
componentDidMount(){
APIService.getBooks().then((data) => {
this.setState({ books: data })
console.log(this.state.data)
})
.catch(function (ex) {
console.log('Response parsing failed. Error: ', ex);
});;
}
- render() - The render() method is the most used lifecycle method. You will see it in all React classes. This is because render() is the only required method within a class component in React. The render() method that actually outputs HTML to the DOM.
- APIService - We are using APIService class to getBooks() method which interns make an API call.
{
this.state.books.map(book =>
<tr key={book.id}>
<td>{book.id}</td>
<td>{book.bookName}</td>
<td>{book.author}</td>
</tr>
)
}
5. App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
import BookComponent from './components/BookComponent';
function App() {
return (
<div>
<header className="container">
<BookComponent />
</header>
</div>
);
}
export default App;
6. Run React App
npm start
yarn start
Comments
Post a Comment
Leave Comment