In this tutorial, you will learn how to integrate a React frontend with a Spring Boot backend to create a full-stack application.
Introduction
Full-stack development combines a frontend (React) with a backend (Spring Boot) to create dynamic web applications. This tutorial shows you how to fetch data from Spring Boot and display it in React.
1. Spring Boot Backend Setup
Create a simple Spring Boot application with a REST controller:
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public List getUsers() {
return List.of(
new User(1, "Alice", "alice@example.com"),
new User(2, "Bob", "bob@example.com")
);
}
}
class User {
private int id;
private String name;
private String email;
// Constructor, getters, and setters
}
2. Enable CORS
To allow React to fetch data from Spring Boot during development:
@CrossOrigin(origins = "http://localhost:5173")
@RestController
@RequestMapping("/api/users")
public class UserController { ... }
3. React Frontend Setup
In your React project, create a Users component:
import { useEffect, useState } from 'react';
function Users() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch('http://localhost:8080/api/users')
.then(res => res.json())
.then(data => setUsers(data))
.catch(err => console.error(err));
}, []);
return (
<div>
<h2>Users</h2>
<ul>
{users.map(user => (
<li key={user.id}>{user.name} - {user.email}</li>
))}
</ul>
</div>
);
}
export default Users;
4. Add Component to App
import Users from './Users.jsx';
function App() {
return (
<div>
<h1>Full-Stack React & Spring Boot</h1>
<Users />
</div>
);
}
export default App;
5. Test Your Full-Stack App
Run Spring Boot on localhost:8080 and React on localhost:5173. You should see the list of users fetched from your backend displayed in React.
6. Summary
In this tutorial, you learned:
- How to set up a Spring Boot backend REST API
- How to handle CORS for frontend-backend communication
- How to fetch backend data in React using
fetch - How to build a basic full-stack application
Next, in React Beginner 10, you will learn how to deploy your React application to production.