In this tutorial, we will demonstrate how to create a React component that allows users to submit new posts via a form and then display a list of the posts they've published, dynamically updating the list whenever a new post is submitted.
We'll be using the free API provided by JSONPlaceholder, specifically the endpoint https://jsonplaceholder.typicode.com/posts to simulate publishing posts.
Follow below step-by-step procedure to build the complete working application.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘post-request-demo’.
Project structure looks like below.
Step 2: Create components folder in src folder and define PublishAndDisplayPost component.
PublishAndDisplayPost.jsx
import { useState } from "react";
export default function PublishAndDisplayPost() {
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [posts, setPosts] = useState([]);
async function createNewPost() {
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts",
{
method: "POST",
body: JSON.stringify({
title: title, // Corrected
body: body, // Corrected
userId: 1,
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
}
);
const responseData = await response.json();
console.log(`responseData : ${JSON.stringify(responseData)}`);
setTitle("");
setBody("");
const newPost = {
title: responseData.title,
body: responseData.body,
};
console.log(`newPost is ${JSON.stringify(newPost)}`);
setPosts([...posts, newPost]); // Corrected
} catch (error) {
console.error("Error:", error);
}
}
return (
<>
<form
onSubmit={(event) => {
event.preventDefault();
createNewPost();
}}
>
<p>
<label htmlFor="title">Provide a title for your post</label>
<input
type="text"
id="title"
name="title"
value={title}
onChange={(event) => {
setTitle(event.target.value);
}}
/>
</p>
<p>
<label htmlFor="body">Provide Body for your post</label>
<textarea
type="text"
id="body"
name="body"
value={body}
rows="10"
cols="50"
onChange={(event) => {
setBody(event.target.value);
}}
/>
</p>
<p>
<button>Submit</button>
</p>
<ul>
{posts.length > 0 ? <h1>Your posts</h1> : ""}
{posts.map((post, index) => (
<li key={index}>
<strong>{post.title}:</strong> {post.body}
</li>
))}
</ul>
</form>
</>
);
}
Step 3: Update main.jsx file with below content.
main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import PublishAndDisplayPost from './components/PublishAndDisplayPost'
createRoot(document.getElementById('root')).render(
<StrictMode>
<PublishAndDisplayPost />
</StrictMode>,
)
Step 4: Build and run the Application by executing below commands.
cd post-request-demo npm install npm run dev
Open the url ‘http://localhost:5173/’ in browser, you will see below screen.
Enter some data to the text
boxes and click on Submit button, you will see the same information below
Submit button.
Previous Next Home




