In this article, we connect React with our .NET Core API to display and add posts in a blog.
✅ 1. Creating the first REST endpoint: GET /posts
In your .NET project, add a new controller for posts:
[ApiController]
[Route("api/[controller]")]
public class PostsController : ControllerBase
{
private readonly IPostRepository _postRepository;
public PostsController(IPostRepository postRepository)
{
_postRepository = postRepository;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
var posts = await _postRepository.GetAllAsync();
return Ok(posts);
}
}
✅ Test the endpoint in Swagger or Postman at GET /api/posts.
🧑💻 2. Consuming the API in React: displaying the posts list
In the React component:
import { useEffect, useState } from 'react';
function PostList() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch("https://localhost:5001/api/posts")
.then(res => res.json())
.then(data => setPosts(data));
}, []);
return (
<div>
<h2>Recent Posts</h2>
<ul>
{posts.map(post => (
<li key={post.slug}>{post.title}</li>
))}
</ul>
</div>
);
}
📝 3. Add post form: POST /posts + validation
React: simple form
function AddPostForm() {
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
await fetch("https://localhost:5001/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title, content })
});
};
return (
<form onSubmit={handleSubmit}>
<input value={title} onChange={e => setTitle(e.target.value)} placeholder="Title" />
<textarea value={content} onChange={e => setContent(e.target.value)} placeholder="Content" />
<button type="submit">Publish</button>
</form>
);
}
.NET: endpoint POST /posts
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreatePostCommand command)
{
var id = await _mediator.Send(command);
return CreatedAtAction(nameof(GetAll), new { id }, null);
}
✅ You can validate data with FluentValidation in the backend and with libraries like react-hook-form in the frontend.