How to Integrate Reactjs with SpringBoot Tutorial

How to integrate SpringBoot and React Example

Tutorial: How to Integrate Reactjs with SpringBoot example.

React is an open-source, front end, JavaScript library for building user interfaces or UI components. React can be used as a base in the development of single-page or mobile. So in the tutorial, I introduce a tutorial: “How to Integrate Reactjs with SpringBoot example” with the details steps and running sourcecode.

Related posts:


Video Guide – Integrate Reactjs with SpringBoot

Overview Tutorial – How to integrate Reactjs with SpringBoot Example

Diagram Architecture - How to Integrate Reactjs and SpringBoot RestAPIs Example
Diagram Architecture – How to Integrate Reactjs and SpringBoot RestAPIs Example

We will build 2 sample projects for the tutorial:
– Frontend: we create a Reactjs project.
– Backend: we create a SpringBoot RestAPIs project.

Goal:

React project structure
React project structure
SpringBoot Project Structure
SpringBoot Project Structure
Integrate successfully between SpringBoot RestAPI and Reactjs
Integrate successfully between SpringBoot RestAPI and Reactjs

Introduce Reactjs

React is a front-end library developed by Facebook. It is used for handling the view layer for web and mobile apps. ReactJS allows us to create reusable UI components.

Reactjs Component

React is all about components, Components are like functions that return HTML elements. Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and returns HTML via a render function.

Example code:

class Customer extends React.Component {
  render() {
    return <h2>Hi, My name is Jane!</h2>;
  }
}

The component has to include the extends React.Component statement, this statement creates an inheritance to React.Component, and gives your component access to React.Component’s functions.
The component also requires a render() method, this method returns HTML.

Display the Customer component in the “root” element:

ReactDOM.render(, document.getElementById('root'));

Components come in two types, Class components (as above example) and Function components, in this tutorial we will concentrate on Class components.

Example Function Component:

function Customer() {
  return <h2>Hi, I'm Jack!</h2>;
}

React Props

React uses props arguments to pass data into React components via HTML attributes.

Example code:


class Customer extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h2>My name is {this.props.name}!</h2>;
  }
}

ReactDOM.render(<Customer name="Jack"/>, document.getElementById('root'));

Reactjs State

React components has a built-in state object where you store property values that belongs to the component.
When the state object changes, the component re-renders.

Example:

class Customer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      firstname: "Jack",
      lastname: "Smith",
      age: "23",
      address: "New York"
    };
  }
  render() {
    return (
      <div>
        <h1>Customer Information</h1>
        <p>
          Firstname: {this.state.firstname}
          Lastname: {this.state.lastname}
          Age: {this.state.age}
		  Address: {this.state.address}
        </p>
      </div>
    );
  }
}

Create Reactjs Project with Create React App

Create React App is a command line utility that generates React projects for you. It’s a convenient tool because it also offers commands that will build and optimize your project for production.
The create-react-app will set up everything you need to run a React application.

– Create a new project in the ReactjsSpringBoot directory with Yarn.

yarn create react-app app
Yarn Create Reactjs project
Yarn Create Reactjs project

Project Structure:

React project structure
React project structure

– App.js code:

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

Start Reactjs application: run yarn start in your app directory:

Running Reactjs application in console
Running Reactjs application in console
Reactjs Application starting
Reactjs Application starting

Create SpringBoot RestAPI

Create a SpringBoot RestAPI project with spring-web dependency:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
       <groupId>org.projectlombok</groupId>
       <artifactId>lombok</artifactId>
       <version>1.18.10</version>
       <scope>provided</scope>
</dependency>

– Define a simple customer model:

package com.loizenai.springboot.reactjs.model;

import lombok.Data;

@Data
public class Customer {
	private String firstname;
	private String lastname;
	private String address;
	private int age;
	private String copyright = "https://loizenai.com";
			
	public Customer(String firstname, String lastname, String address, int age) {
		this.firstname = firstname;
		this.lastname = lastname;
		this.address = address;
		this.age = age;
	}	
}

Now we build a simple GET RestAPI as below code:

package com.loizenai.springboot.reactjs.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.loizenai.springboot.reactjs.model.Customer;

@RestController
@RequestMapping("/api")
public class CustomerController {

    @GetMapping("/customer")
    Customer customer() {
    	return new Customer("Jack", "Smith", "374 William S Canning Blvd", 23);
    }    
}

SpringBoot Project Structure:

SpringBoot Project Structure
SpringBoot Project Structure

Run the SpringBoot application and check the result:

SpringBoot Get RestAPI
SpringBoot Get RestAPI

Reactjs use Ajax to Fetch data from SpringBoot RestAPI

Modify app/src/App.js to use the following code that calls /api/customer and display the response-body in the UI:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  state = {
    isLoading: true,
    groups: []
  };

  async componentDidMount() {
    const response = await fetch('/api/customer');
    const body = await response.json();
    this.setState({ customer: body, isLoading: false });
  }

  render() {
    const {customer, isLoading} = this.state;

    if (isLoading) {
      return <p>Loading...</p>;
    }

    return (
      <div className="App">
        <h2>Customer Info</h2>
          Firstname: {customer.firstname}<br/>
          Lastname: {customer.lastname}<br/>
          Age: {customer.age}<br/>
          Address: {customer.address}<br/>
          Copyrightby: <a href="{customer.copyright}">{customer.copyright}</a><br/>
      </div>
    );
  }
}

export default App;

In the function componentDidMount(), we implement a Get Ajax to fetch data from SpringBoot RestAPI then save it in state object of React application.

To proxy from /api to http://localhost:8080/api, add a proxy setting to app/package.json:

"scripts": {...},
"proxy": "http://localhost:8080",

Make sure Spring Boot is running, then re-start Reactjs application by cmd: yarn start in your app directory:

React application in Web-browser
React application in Web-browser

What is function componentDidMount()?

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases: Mounting, Updating, and Unmounting.

Mounting means putting elements into the DOM with four built-in methods that gets called, in this order, when mounting a component:

  1. the constructor() method is called before anything else, when the component is initiated and it is the natural place to set up the initial state and other initial values.
  2. the getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM. This is the natural place to set the state object based on the initial props.
  3. the render() method is required, and is the method that actually outputs the HTML to the DOM.
  4. the componentDidMount() method is called after the component is rendered. This is where you run statements that requires that the component is already placed in the DOM.

The render() method is required and will always be called, the others are optional and will be called if you define them.

Read more: React State and Life-cycle

Build Reactjs Application and Integrate with SpringBoot project

Build Reactjs application by cmd yarn build

-> result:

Reactjs Build production
Reactjs Build production

After the building process, it creates a build folder as below image:

Check the build production of Reactjs application
Check the build production of Reactjs application

– Copy all files in the new build folder of React project to static folder of SpringBoot project, re-start SpringBoot project:

SpringBoot integrate with Reactjs Production Build
SpringBoot integrate with Reactjs Production Build
Integrate successfully between SpringBoot RestAPI and Reactjs
Integrate successfully between SpringBoot RestAPI and Reactjs

Cheer! Integrate Successfully between SpringBoot and Reactjs Application.

Further Reading

Related posts:


Sourcecode – How to Integrate Reactjs with SpringBoot example

Full Sourcecodes: Reactjs + SpringBoot

1. Reactjs

Reactjs

2. SpringBoot RestAPI

SpringBoot RestAPI

– Github Sourcecode:

1. Reactjs.

Reactjs – Github

2. SpringBoot RestAPI:

SpringBoot RestAPI – Github

Leave a Reply

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