React and Spring Boot Integration




Hey guys in this post, we will discuss about integrating React with Spring boot application. We will create a REST end point in Spring boot and we will consume that REST end point from react application.

Read More:

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following 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.5.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>springbootrestapi</artifactId>
	<version>1.0.0</version>
	<name>springbootrestapi</name>
	<description>Spring boot rest api</description>
	<properties>
		<java.version>16</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>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Open the main class


Open the base class that contains main(), create a REST end point /welcome

package in.bushansirgur.springbootrestapi;

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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
@CrossOrigin("*")
@RequestMapping("/api")
public class SpringbootrestapiApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootrestapiApplication.class, args);
	}

	@GetMapping("/welcome")
	public String helloWorld() {
		return "Hello World! Welcome to Spring boot and React Hooks!";
	}
}

Run the Spring Boot app


Run the application using the below maven command –

mvn spring-boot:run

Open the browser and navigate to the URL http://localhost:8080/api/welcome

Screenshot-2021-09-04-at-8-23-10-PM

Create React Project


In order create react project, first we should install Node.js. Download the Node.js from the below link and install on your system

https://nodejs.org/en/download/

Once Node.js is installed on your system, you can verify it by executing the below command

node -v

To create new react project, we can use create-react-app library. Open the command prompt, enter the following command

npx create-react-app my-app

This will create react starter project. Next open the project in any text editor

Install axios library


On the root of the project, enter the following command to install axios library

npm install axios
  • Axios is a simple promise based HTTP client for the browser and node.js.
  • Axios provides a simple to use library in a small package with a very extensible interface.

Consume the REST end point


Open App.js file, remove the existing code and add the following content

import axios from 'axios';
import { useEffect, useState } from 'react';
import './App.css';

const App = () => {
  let basePath = 'http://localhost:8080/api';
  const [data, setData] = useState('');

  useEffect(() => {
    axios.get(basePath+'/welcome')
    .then(function (response) {
      setData(response.data);
    })
    .catch(function (error) {
      console.log('Error:', error);
    })
  }, []);

  return (
    <div className="App">
      <p>{data}</p>
    </div>
  );
}

export default App;
  • useState is one of build-in react hooks available in 0.16.7 version.
  • useState should be used only inside functional components.
  • useState is the way if we need an internal state and don’t need to implement more complex logic such as lifecycle methods.

Run the React app


On the root of the project, open the command prompt, execute the following command

npm start

This will run the application on the port, localhost:3000
Screenshot-2021-09-04-at-8-25-00-PM

That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.



About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *