Category : React JS | Sub Category : React JS | By Prasad Bonam Last updated: 2023-11-16 14:24:38 Viewed : 220
To submit form data with React on the front end and a Spring Boot application on the back end, you will need to follow several steps. I will provide a basic example to guide you through the process.
Create a React Component with a Form:
Create a new React component (MyForm.js
, for example) with a form that includes input fields for the data you want to submit. Use the useState
hook to manage the form data.
jsximport React, { useState } from `react`;
const MyForm = () => {
const [formData, setFormData] = useState({
firstName: ``,
lastName: ``,
email: ``,
});
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
// Call a function to send the data to the backend
submitFormData();
};
const submitFormData = async () => {
try {
const response = await fetch(`http://localhost:8080/api/submit`, {
method: `POST`,
headers: {
`Content-Type`: `application/json`,
},
body: JSON.stringify(formData),
});
const data = await response.json();
console.log(`Data submitted successfully:`, data);
} catch (error) {
console.error(`Error submitting data:`, error);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
First Name:
<input
type="text"
name="firstName"
value={formData.firstName}
onChange={handleChange}
/>
</label>
<br />
<label>
Last Name:
<input
type="text"
name="lastName"
value={formData.lastName}
onChange={handleChange}
/>
</label>
<br />
<label>
Email:
<input
type="text"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
Create a Spring Boot Controller: Create a Spring Boot controller that handles the incoming POST requests and processes the form data.
javaimport org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class FormController {
@PostMapping("/submit")
public String submitForm(@RequestBody FormData formData) {
// Process the form data (you can save it to a database, etc.)
System.out.println("Received form data: " + formData.toString());
return "Form data submitted successfully!";
}
}
Don`t forget to create a FormData
class to represent the structure of the incoming JSON data.
javapublic class FormData {
private String firstName;
private String lastName;
private String email;
// Getters and setters
}
Enable Cross-Origin Resource Sharing (CORS):
If your React app is running on a different server, you need to configure CORS in your Spring Boot application. You can do this by adding the @CrossOrigin
annotation to your controller or by configuring it globally. For example:
javaimport org.springframework.web.bind.annotation.CrossOrigin;
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:3000") // Replace with your React app`s URL
public class FormController {
// Controller code remains the same
}
Run Your Spring Boot Application:
Ensure that your Spring Boot application is running at http://localhost:8080
(or the port you specified).
bash./mvnw spring-boot:run
Run Your React Application: Start your React application using the following command:
bashnpm start
Visit http://localhost:3000
(or the port specified by your React app) in your browser.
Submit the Form: Fill out the form in your React application and click the submit button. You should see the form data logged in your Spring Boot application console.
This example provides a basic setup for submitting form data from React to Spring Boot. Depending on your requirements, you may need to enhance error handling, add validation, or modify the backend processing logic.
Lets break down the code snippet:
jsximport React, { useState } from `react`;
const MyForm = () => {
const [formData, setFormData] = useState({
firstName: ``,
lastName: ``,
email: ``,
});
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value,
});
};
const handleSubmit = (e) => {
e.preventDefault();
// Call a function to send the data to the backend
submitFormData();
};
// Additional code for submitFormData function goes here
return (
<form onSubmit={handleSubmit}>
{/* Form input fields */}
</form>
);
};
export default MyForm;
Import Statements:
import React, { useState } from `react`;
: Imports the React
library and the useState
hook from the react
package. The useState
hook is used for managing state in functional components.Functional Component Definition:
const MyForm = () => { ... }
: Defines a functional component named MyForm
.State Initialization using useState
:
const [formData, setFormData] = useState({ firstName: ``, lastName: ``, email: `` });
: Initializes a state variable named formData
using the useState
hook. formData
is an object with three properties (firstName
, lastName
, and email
), and setFormData
is a function that allows updating the state.Event Handler (handleChange
):
const handleChange = (e) => { ... }
: Defines a function handleChange
that is triggered whenever there is a change in the input fields. It uses the spread operator (...
) to create a shallow copy of the existing formData
and updates the specific property (e.target.name
) with the new value (e.target.value
). This ensures immutability when updating state.Event Handler (handleSubmit
):
const handleSubmit = (e) => { ... }
: Defines a function handleSubmit
that is triggered when the form is submitted. It prevents the default form submission behavior (e.preventDefault()
) to handle form submission manually. In this case, it calls a function (submitFormData()
) to send the form data to the backend.Return Statement:
return ( ... )
: Returns JSX that represents the structure of the component. In this case, it returns a <form>
element with an onSubmit
event handler set to handleSubmit
. The actual form input fields would be placed inside this form element.This component represents a basic form in React that utilizes the useState
hook to manage form data and provides event handlers for handling input changes (handleChange
) and form submission (handleSubmit
). The actual logic for sending form data to the backend (submitFormData()
) is intended to be implemented based on specific requirements.
const submitFormData = async () => {
try {
const response = await fetch(`http://localhost:8080/api/submit`, {
method: `POST`,
headers: {
`Content-Type`: `application/json`,
},
body: JSON.stringify(formData),
});
// Additional code for handling the response goes here
} catch (error) {
console.error(`Error submitting data:`, error);
}
};
Function Declaration:
const submitFormData = async () => { ... }
: Declares an asynchronous arrow function named submitFormData
. The async
keyword indicates that the function will perform asynchronous operations and may use await
.Try-Catch Block:
try { ... } catch (error) { ... }
: Wraps the code in a try-catch
block. This is a common pattern for handling asynchronous operations where errors might occur. If any error occurs within the try
block, it will be caught and handled in the catch
block.HTTP Request using fetch
:
const response = await fetch(`http://localhost:8080/api/submit`, { ... });
: Uses the fetch
function to make an HTTP request to the specified URL (http://localhost:8080/api/submit
). It is a POST request (method: `POST`
) and includes headers specifying that the content type is JSON (Content-Type: application/json
). The request body is the JSON representation of the formData
object (body: JSON.stringify(formData)
).Handling the Response (Placeholder):
// Additional code for handling the response goes here
). Depending on your use case, you may want to process the response data, check the status, and perform further actions accordingly.jsxconst responseData = await response.json();
console.log(`Response from server:`, responseData);
// Perform additional actions based on the response
Error Handling:
catch (error) { console.error(`Error submitting data:`, error); }
: If any error occurs during the HTTP request (e.g., network issues, server errors), it will be caught in the catch
block, and an error message will be logged to the console.This function is responsible for making an asynchronous HTTP POST request to the specified endpoint (http://localhost:8080/api/submit
) with the form data serialized as JSON. The actual logic for handling the response and any additional actions based on the server`s response should be implemented in the // Additional code for handling the response goes here
section.