Form Handling in React and Spring boot, API Integration complete Full Stack Application

Overview

In this tutorial, We are focusing on creating a complete web application using React and Spring Boot, with an emphasis on form handlings. The tutorial covers all aspects of form handling, API creation, and database integration, utilizing React for the frontend

Form Handling in React and Spring Boot

Table of Contents:

  • Setting Up the React Application
  • Creating and Handling the Form in React
  • Set up the Spring Boot application (server)
  • Configure the application.properties file to connect the database.
  • Creating the Entity, Repository, Service and Controller for API
  • Connect Frontend and Backend for calling the Spring Boot api using React

Now let’s create the complete full stack web application and understand the form handling in react and spring boot

Step 1: Setting Up the React Application

The first step to creating a React application using the command npx create-react-app with you application name like following

npx create-react-app FormHanding 

After installation, the React application is run using the command npm start and test you application is running or not

npx start 

Step 2: Creating and Handling the Form in React


import { useState } from 'react';
import axios from 'axios';

function App() {

  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    contactNumber: "",
    address: "",
    city: "",
    state: "",
    country: "",
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prevFormData) => ({ ...prevFormData, [name]: value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(formData);

    //hare we call the spring boot api for saving the data into the database
  };

  return (
    <div className="App">
      <h2>Form Handling</h2>

      <form onSubmit={handleSubmit}>
        <div>
          <label>First Name:</label>
          <input type="text" name="firstName" value={formData.firstName} onChange={handleChange} />
        </div>

        <br/>
        <div>
          <label>Last Name:</label>
          <input type="text" name="lastName" value={formData.lastName} onChange={handleChange} />
        </div>

        <br/>
        <div>
          <label>Email:</label>
          <input type="email" name="email" value={formData.email} onChange={handleChange} />
        </div>

        <br/>
        <div>
          <label>Contact Number:</label>
          <input type="tel" name="contactNumber" value={formData.contactNumber} onChange={handleChange} />
        </div>

        <br/>
        <div>
          <label>Address:</label>
          <input type="text" name="address" value={formData.address} onChange={handleChange} />
        </div>

        <br/>
        <div>
          <label>City:</label>
          <input type="text" name="city" value={formData.city} onChange={handleChange} />
        </div>

        <br/>
        <div>
          <label>State:</label>
          <input type="text" name="state" value={formData.state} onChange={handleChange} />
        </div>

        <br/>
        <div>
          <label>Country:</label>
          <input type="text" name="country" value={formData.country} onChange={handleChange} />
        </div>

        <br/><br/>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

export default App;

Key Concepts:

  • State Management: The useState hook is used to manage the form data. formData is an object holding the state of all form fields (firstName, lastName, etc.). setFormData is a function to update the state whenever a user types into an input field.
  • Dynamic Input Handling: The handleChange function is triggered whenever a form input changes. It updates the formData object dynamically using the name attribute of the input fields, ensuring all fields are managed in a single state object.
  • Form Submission: The handleSubmit function is triggered when the form is submitted. It prevents the default form submission behavior using e.preventDefault() to handle the process via JavaScript. The form data (formData) is logged to the console for debugging purposes.

Step 3: Set up the Spring Boot application (server)

Use Spring Initializer or an IDE like IntelliJ or Eclipse to create a new Spring Boot project. Add the following dependencies:

  • Spring Web: For building web applications and REST APIs.
  • Spring Data JPA: For interacting with the database.
  • MySQL Driver: To connect to your MySQL database.

Step 4 : Configure the application.properties File

1. Open the application.properties file and configure your database settings. Here’s an example configuration:

2. Replace your_database_name, your_username, and your_password with your database details.


# Server configuration
server.port = 8081
          
# Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.name=your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
          
# JPA configuration
spring.jpa.hibernate.ddl-auto=update
        

For More Details:

If you want to learn more about configuring the application.properties file, check out this detailed article:

Create REST APIs Using Spring Boot: Step-by-Step Guide

Step 5 : Creating the Entity, Repository, Service and Controller for our API

  • Entity Classes: Representing the database table.
  • Controller: Defining the endpoints of the API.
  • Service: Containing the business logic.
  • Repository: Performing database operations.

Let’s create each of these components step by step.

Entity Class (UserData)


@Entity
public class UserData {

    private String firstName;
    private String lastName;

    @Id
    private String email;

    private String contactNumber;
    private String address;
    private String city;
    private String state;
    private String country;

    // Parameterized constructor
    public UserData(String firstName, String lastName, String email, 
                      String contactNumber, String address, 
                      String city, String state, String country) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.contactNumber = contactNumber;
        this.address = address;
        this.city = city;
        this.state = state;
        this.country = country;
    }

    // Non-parameterized constructor
    public UserData() {
    }

    // Getters and Setters
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

}

Controller (for defining api endpoint)


@RestController
public class UserDataController {

    @Autowired
    private UserDataService userDataService;

    @PostMapping("/saveUserData")
    @CrossOrigin(origins = "http://localhost:3000")
    public UserData save(@RequestBody UserData userData) {
        return userDataService.save(userData);
    }
}

Service


@Service
public class UserDataService {

    @Autowired
    private UserDataRepository userDataRepository;

    public UserData save(UserData userData) {
        return userDataRepository.save(userData);
    }
}

Repository


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

import com.crudAPI.example.entity.Students;

@Repository
public interface StudentRepo extends JpaRepository<Students, Integer> {

}

Project Structure

Here’s an image showing project structure for our spring boot application

project structure form handling in spring boot

Run the Application

Run your Spring Boot application. It will automatically create the table in your database based on the UserData entity.

user_data table with empty data

Step 6 Connect Frontend and Backend for calling the Spring Boot api using React

The React application is configured to make API calls to the Spring Boot server or application using Axios for HTTP requests


    const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(formData);

    let apiUrl = 'http://localhost:8082/saveUserData';

    try {
      const response = await axios.post(apiUrl, formData);
      console.log(response);
    } catch (error) {
      console.log("Error occurred while API calling: " + error);
    }
  };

Let’s break down this code step by step in the context of calling a Spring Boot API from a React application using Axios:

let apiUrl = 'http://localhost:8082/saveUserData';

apiUrl:

  • This is the URL of the API endpoint you want to call.
  • http://localhost:8082/saveUserData is the endpoint of your Spring Boot backend running locally on port 8082.
  • This endpoint is expected to handle a POST request and save user data sent from the React frontend.

    // API call to send data to server
    try {
      const response = await axios.post(apiUrl, formData);
      console.log(response);
    } catch (error) {
      console.log("Error occurred while API calling: " + error);
    }

axios.post():

  • axios is a library used to make HTTP requests from the frontend to the backend.
  • .post() is used to send data to the server using the HTTP POST method. It’s typically used when creating or updating resources on the server.
  • apiUrl: The URL where the Spring Boot API is located. In this case, it is http://localhost:8082/saveUserData.
  • formData: This is the data you want to send to the backend. The data is gathered from the form fields (e.g., first name, last name, email, etc.) and stored in the formData object.

await:

  • await is used to stop the execution of the function until the asynchronous operation (the API call in this case) completes. This means that the next line of code will not run until the POST request is completed (either successfully or with an error).
  • Using await ensures that the result of the API call (whether successful or not) is handled before continuing with any other code in the async function.

response:

  • If the request is successful, response will contain the data returned from the Spring Boot API.
  • You can get or access the response data (the data sent by the backend) using response.data. In this case, we’re just printing the entire response object to the console.

catch block:

  • If there’s an error occurred while API calling (for example, the backend is down, incorrect endpoint, bad network connection), the catch block will be executed.
  • The error is caught and logged the message to the console. The message “error occurred while api calling ” is concatenated with the actual error message for debugging purposes.

Now let’s fill the details in forms and submit

api calling in react using axios

You can check in the browser’s network tab if the API has been called or not. In the above image, it is saving the data to the database and returning the same data after saving it. Now, let’s check the database to see if the data has been entered or not.

user_data table with inserted data

The tutorial concludes with a demonstration of submitting the form and successfully saving the data to the database, showcasing the integration of React and Spring Boot

Youtube Video –

Github Repository –

https://github.com/amangupta7024/FormHandling-in-React-Spring-Boot

Explore our more articles

Form Handling in React and Spring Boot Complete Full Stack Web Application with step-by-step guide

In this tutorial, We are focusing on creating a complete web application using React and Spring Boot, with an emphasis on form handlings. following is the steps

1. Setting Up the React Application
2. Creating and Handling the Form in React
3. Set up the Spring Boot application (server)
4. Configure the application.properties file to connect the database.
5. Creating the Entity, Repository, Service and Controller for API
6. Connect Frontend and Backend for calling the Spring Boot api using React

1 thought on “Form Handling in React and Spring boot”

Leave a Comment