Spring Boot + React Typescript example

In this tutorial, we will learn how to build a full stack Spring Boot + React Typescript example with a CRUD App. The back-end server uses Spring Boot with Spring Web MVC for REST APIs and Spring Data JPA for interacting with embedded database (H2 database). Front-end side is made with React Typescript, React Router, Axios & Bootstrap.

Related Posts:
React + Spring Boot: Pagination example
Spring Boot + React: Login example with JWT Authentication & Spring Security
React Upload/Download Files to/from Spring Boot Rest Apis
React Custom Hook in Typescript example

Run both projects in one place:
How to integrate React with Spring Boot

You can use one of following backend for other Databases:


Spring Boot + React Typescript example Overview

We will build a full-stack Spring Boot & React Typescript Tutorial Application in that:

  • Each Tutorial has id, title, description, published status.
  • We can create, retrieve, update, delete Tutorials.
  • We can also find Tutorials by title.

The images below shows screenshots of our System.

– Create a Tutorial:

spring-boot-react-typescript-crud-create-tutorial

– Retrieve all Tutorials:

spring-boot-react-typescript-crud-retrieve-tutorial

– Click on Edit button to retrieve an item:

spring-boot-react-typescript-crud-retrieve-one-tutorial

On this Page, you can:

  • change status to Published using Publish button
  • remove the Tutorial from Database using Delete button
  • update the Tutorial details on Database with Update button

spring-boot-react-typescript-crud-update-tutorial

– Search items by title:

spring-boot-react-typescript-crud-search-tutorial

Architecture of Spring Boot React Typescript example

This is the application architecture we’re gonna build:

spring-boot-react-typescript-crud-architecture

– Spring Boot exports REST Apis using Spring Web MVC & interactsrations & finder methods with Spring D
– React Client sends HTTP Requests and retrieves HTTP Responses using Axios. React Router is used for navigating to pages.

You can also find the Spring Restful Apis that works with other databases here:
Spring JPA + PostgreSQL
Spring JPA + MySQL
Spring Data + MongoDB
Spring JPA + SQL Server
Spring JPA + Oracle
Spring Data + Cassandra

Spring Boot Rest Apis Back-end

Overview

These are APIs that Spring Boot App will export:

Methods Urls Actions
POST /api/tutorials create new Tutorial
GET /api/tutorials retrieve all Tutorials
GET /api/tutorials/:id retrieve a Tutorial by :id
PUT /api/tutorials/:id update a Tutorial by :id
DELETE /api/tutorials/:id delete a Tutorial by :id
DELETE /api/tutorials delete all Tutorials
GET /api/tutorials?title=[keyword] find all Tutorials which title contains keyword

– We make CRUD operations & finder methods with Spring Data JPA’s JpaRepository.
– The database will be H2 Database (in memory or on disk) by configuring project dependency & datasource.

Technology

  • Java 8
  • Spring Boot 2.7 (with Spring Web MVC, Spring Data JPA)
  • H2 Database
  • Maven 3.6.1

Project Structure

spring-boot-react-typescript-server-project

Tutorial data model class corresponds to entity and table tutorials.
TutorialRepository is an interface that extends JpaRepository for CRUD methods and custom finder methods. It will be autowired in TutorialController.
TutorialController is a RestController which has request mapping methods for RESTful requests such as: getAllTutorials, createTutorial, updateTutorial, deleteTutorial, findByPublished
– Configuration for Spring Datasource, JPA & Hibernate in application.properties.
pom.xml contains dependencies for Spring Boot and H2 Database.

Create & Setup Spring Boot project

Use Spring web tool or your development tool (Spring Tool Suite, Eclipse, Intellij) to create a Spring Boot project.

Then open pom.xml and add these dependencies:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>

Configure Spring Boot, JPA, h2, Hibernate

Under src/main/resources folder, open application.properties and write these lines.

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
 
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update

spring.h2.console.enabled=true
# default path: h2-console
spring.h2.console.path=/h2-ui
  • spring.datasource.url: jdbc:h2:mem for In-memory database and jdbc:h2:file for disk-based database.
  • spring.datasource.username & spring.datasource.password properties are the same as your database installation.
  • Spring Boot uses Hibernate for JPA implementation, we configure H2Dialect for H2 Database
  • spring.jpa.hibernate.ddl-auto is used for database initialization. We set the value to update value so that a table will be created in the database automatically corresponding to defined data model. Any change to the model will also trigger an update to the table. For production, this property should be validate.
  • spring.h2.console.enabled=true tells the Spring to start H2 Database administration tool and you can access this tool on the browser: http://localhost:8080/h2-console.
  • spring.h2.console.path=/h2-ui is for H2 console’s url, so the default url http://localhost:8080/h2-console will change to http://localhost:8080/h2-ui.

Define Data Model

Our Data model is Tutorial with four fields: id, title, description, published.
In model package, we define Tutorial class.

model/Tutorial.java

package com.bezkoder.spring.datajpa.model;

import javax.persistence.*;

@Entity
@Table(name = "tutorials")
public class Tutorial {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;

	@Column(name = "title")
	private String title;

	@Column(name = "description")
	private String description;

	@Column(name = "published")
	private boolean published;

	...
}

@Entity annotation indicates that the class is a persistent Java class.
@Table annotation provides the table that maps this entity.
@Id annotation is for the primary key.
@GeneratedValue annotation is used to define generation strategy for the primary key. GenerationType.AUTO means Auto Increment field.
@Column annotation is used to define the column in database that maps annotated field.

Create Repository Interface

Let’s create a repository to interact with Tutorials from the database.
In repository package, create TutorialRepository interface that extends JpaRepository.

repository/TutorialRepository.java

package com.bezkoder.spring.datajpa.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import com.bezkoder.spring.datajpa.model.Tutorial;

public interface TutorialRepository extends JpaRepository<Tutorial, Long> {
  List<Tutorial> findByPublished(boolean published);

  List<Tutorial> findByTitleContaining(String title);
}

Now we can use JpaRepository’s methods: save(), findOne(), findById(), findAll(), count(), delete(), deleteById()… without implementing these methods.

We also define custom finder methods:
findByPublished(): returns all Tutorials with published having value as input published.
findByTitleContaining(): returns all Tutorials which title contains input title.

The implementation is plugged in by Spring Data JPA automatically.

You can modify this Repository:
– to work with Pagination, the instruction can be found at:
Spring Boot Pagination & Filter example | Spring JPA, Pageable
– or to sort/order by multiple fields with the tutorial:
Spring Data JPA Sort/Order by multiple Columns | Spring Boot

You also find way to write Unit Test for this JPA Repository at:
Spring Boot Unit Test for JPA Repositiory with @DataJpaTest

Create Spring Rest APIs Controller

Finally, we create a controller that provides APIs for creating, retrieving, updating, deleting and finding Tutorials.

controller/TutorialController.java

package com.bezkoder.spring.datajpa.controller;
...

@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/api")
public class TutorialController {

  @Autowired
  TutorialRepository tutorialRepository;

  @GetMapping("/tutorials")
  public ResponseEntity<List<Tutorial>> getAllTutorials(@RequestParam(required = false) String title) {
    ...
  }

  @GetMapping("/tutorials/{id}")
  public ResponseEntity<Tutorial> getTutorialById(@PathVariable("id") long id) {
    ...
  }

  @PostMapping("/tutorials")
  public ResponseEntity<Tutorial> createTutorial(@RequestBody Tutorial tutorial) {
    ...
  }

  @PutMapping("/tutorials/{id}")
  public ResponseEntity<Tutorial> updateTutorial(@PathVariable("id") long id, @RequestBody Tutorial tutorial) {
    ...
  }

  @DeleteMapping("/tutorials/{id}")
  public ResponseEntity<HttpStatus> deleteTutorial(@PathVariable("id") long id) {
    ...
  }

  @DeleteMapping("/tutorials")
  public ResponseEntity<HttpStatus> deleteAllTutorials() {
    ...
  }

  @GetMapping("/tutorials/published")
  public ResponseEntity<List<Tutorial>> findByPublished() {
    ...
  }
}

@CrossOrigin is for configuring allowed origins.
@RestController annotation is used to define a controller and to indicate that the return value of the methods should be be bound to the web response body.
@RequestMapping("/api") declares that all Apis’ url in the controller will start with /api.
– We use @Autowired to inject TutorialRepository bean to local variable.

You can continue with step by step to implement this Spring Boot Server in the post:
Spring Boot JPA + H2 example: Build a CRUD Rest APIs

Run the Spring Boot Server

Run Spring Boot application with command: mvn spring-boot:run.

React Typescript Front-end

Overview

This is React Typescript components that we’re gonna implement:

spring-boot-react-typescript-client-overview

– The App component is a container with React Router. It has navbar that links to routes paths.

TutorialsList gets and displays Tutorials.
Tutorial has form for editing Tutorial’s details based on :id.
AddTutorial has form for submission new Tutorial.

– They call TutorialDataService functions which use axios to make HTTP requests and receive responses.

If you want to work with Redux like this:

react-hooks-redux-crud-example-components

Please visit: React Hooks + Redux: CRUD example with Axios and Rest API

Technology

  • React 17/16
  • typescript 4.3.5
  • react-router-dom 6
  • axios 0.26.1
  • bootstrap 4.6.0

Project Structure

spring-boot-react-typescript-client-project

Let me explain it briefly.

package.json contains 5 main modules: react, typescript, react-router-dom, axios & bootstrap.
App is the container that has Router & navbar.
types/Tutorial.ts exports ITutorialData interface.
– There are 3 components: TutorialsList, Tutorial, AddTutorial.
http-common.ts initializes axios with HTTP base Url and headers.
TutorialService has methods for sending HTTP requests to the Apis.
.env configures port for this React CRUD App.

Setup React Typescript Project

Open cmd at the folder you want to save Project folder, run command:
npx create-react-app react-typescript-api-call --template typescript

After the process is done. We create additional folders and files like the following tree:


public

src

components

AddTutorial.tsx

Tutorial.tsx

TutorialsList.tsx

services

TutorialService.ts

types

Tutorial.ts

App.css

App.tsx

index.tsx

package.json


Import Bootstrap for React Typescript Project

Run command: npm install [email protected].

Open src/App.tsx and modify the code inside it as following-

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";

function App() {
  return (
    // ...
  );
}

export default App;

Add React Router to React Typescript Project

– Run the command: npm install react-router-dom.
– Open src/index.tsx and wrap App component by BrowserRouter object.

import ReactDOM from 'react-dom';
import { BrowserRouter } from "react-router-dom";

import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

reportWebVitals();

Add Navbar to React Typescript Project

Open src/App.tsx, this App component is the root container for our application, it will contain a navbar, and also, a Switch object with several Route. Each Route points to a React Component.

import { Routes, Route, Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";

import AddTutorial from "./components/AddTutorial";
import Tutorial from "./components/Tutorial";
import TutorialsList from "./components/TutorialsList";

const App: React.FC = () => {
  return (
    <div>
      <nav className="navbar navbar-expand navbar-dark bg-dark">
        <a href="/tutorials" className="navbar-brand">
          bezKoder
        </a>
        <div className="navbar-nav mr-auto">
          <li className="nav-item">
            <Link to={"/tutorials"} className="nav-link">
              Tutorials
            </Link>
          </li>
          <li className="nav-item">
            <Link to={"/add"} className="nav-link">
              Add
            </Link>
          </li>
        </div>
      </nav>

      <div className="container mt-3">
        <Routes>
          <Route path="/" element={<TutorialsList/>} />
          <Route path="/tutorials" element={<TutorialsList/>} />
          <Route path="/add" element={<AddTutorial/>} />
          <Route path="/tutorials/:id" element={<Tutorial/>} />
        </Routes>
      </div>
    </div>
  );
}

export default App;

Define Data Type

Now we need to define the data type for Tutorial. Create and export ITutorialData interface in types/Tutorial.ts.

export default interface ITutorialData {
  id?: any | null,
  title: string,
  description: string,
  published?: boolean,
}

Initialize Axios for React Typescript example

Let’s install axios with command: npm install axios.
Under src folder, we create http-common.ts file with following code:

import axios from "axios";

export default axios.create({
  baseURL: "http://localhost:8080/api",
  headers: {
    "Content-type": "application/json"
  }
});

You can change the baseURL that depends on REST APIs url that your Server configures.

For more details about ways to use Axios, please visit:
Axios request: Get/Post/Put/Delete example

Create Data Service

In this step, we’re gonna create a service that uses axios object above to send HTTP requests.
The service exports CRUD functions and finder method:

  • CREATE: create
  • RETRIEVE: getAll, get
  • UPDATE: update
  • DELETE: remove, removeAll
  • FINDER: findByTitle

services/TutorialService.ts

import http from "../http-common";
import ITutorialData from "../types/Tutorial";

const getAll = () => {
  return http.get<Array<ITutorialData>>("/tutorials");
};

const get = (id: any) => {
  return http.get<ITutorialData>(`/tutorials/${id}`);
};

const create = (data: ITutorialData) => {
  return http.post<ITutorialData>("/tutorials", data);
};

const update = (id: any, data: ITutorialData) => {
  return http.put<any>(`/tutorials/${id}`, data);
};

const remove = (id: any) => {
  return http.delete<any>(`/tutorials/${id}`);
};

const removeAll = () => {
  return http.delete<any>(`/tutorials`);
};

const findByTitle = (title: string) => {
  return http.get<Array<ITutorialData>>(`/tutorials?title=${title}`);
};

const TutorialService = {
  getAll,
  get,
  create,
  update,
  remove,
  removeAll,
  findByTitle,
};

export default TutorialService;

We call axios (imported as http) get, post, put, delete method corresponding to HTTP Requests: GET, POST, PUT, DELETE to make CRUD Operations.

You can simplify import statement with:
Absolute Import in React

Create React Typescript Components

Now we’re gonna build 3 components (pages) corresponding to 3 Routes defined before.

  • Add new Item
  • List of items
  • Item details

You can continue with step by step to implement this React Typescript App in the post:
React Typescript with API call example

Run React Typescript Client

You can run our App with command: npm start or yarn start.
If the process is successful, open Browser with Url: http://localhost:8081/ and check it.

Source Code

You can find Github source code for this tutorial at: Spring Boot and React Project Github

Conclusion

Today we have an overview of React Typescript + Spring Boot example when building a full-stack CRUD Application.

We also take a look at client-server architecture for REST API using Spring Boot and Spring Data JPA with embedded H2 database, as well as React Redux project structure for building a front-end app to make HTTP requests and consume responses.

Next tutorials show you more details about how to implement the system (including source code):
– Back-end:

– Front-end: React Typescript

You will want to know how to run both projects in one place:
How to integrate React with Spring Boot

With Pagination:
React Pagination with API using Material-UI

react-pagination-with-api-material-ui-change-page

Or Serverless with Firebase:
React Firebase CRUD with Realtime Database
React Firestore CRUD App example | Firebase Cloud Firestore

Happy learning, see you again!

One thought to “Spring Boot + React Typescript example”

  1. I would have a question. There is an other Angular CRUD project with Spring Boot where Tutorials are stored. How could these 2 projects be combined?
    For example a moderator can add tutorials and edit them. A user can only see them.

    How would the tutorial model be connected in both back and frontend?

    Thank you for the answer,
    Best regards

Comments are closed to reduce spam. If you have any question, please send me an email.