Master React From Scratch

Clear, practical, and structured React lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to React
Introduction to React What Is React? Features of React Advantages of React Limitations of React Uses of React React vs JavaScript React Architecture
2. React Getting Started
Getting Started Introduction Prerequisites Installing Node.js and npm Creating a React Project with Vite React Project Structure Running React Application Your First React Application
3. JSX
JSX Introduction What Is JSX? JavaScript Expressions JSX Attributes Rendering JSX Elements JSX Children React Fragments JSX Rules and Best Practices JSX vs HTML
4. React Components
Components Introduction Functional Components Class Components Component Composition Reusable Components Component Tree Component Lifecycle Import and Export Components
5. React Props
Props Introduction What Are Props? Passing Props to Components Props Destructuring Default Props Values Children Props Typing Props with TypeScript Props vs State
6. React State
State Introduction What Is State? useState Hook Updating State Functional State Updates State with Objects State with Arrays State Immutability Lifting State Up
7. React Events
Events Introduction Handling Events Passing Arguments to Event Handlers Synthetic Events Form Events Keyboard and Mouse Events Event Propagation
8. Conditional Rendering
Conditional Rendering Introduction If-Else Rendering Ternary Operator Logical AND Operator Element Variables Preventing Rendering Multiple Conditions Conditional CSS Classes
9. Lists and Keys
Lists and Keys Introduction Rendering Lists with map() Understanding Keys Choosing Unique Keys Lists of Objects Filtering Lists Sorting Lists Empty Lists and Conditional Rendering
10. React Forms
Forms Introduction Handling Forms Controlled Components Uncontrolled Components Handling Input Fields Checkboxes and Radio Buttons Select and Textarea Form Validation Form Submission
11. React Hooks
Hooks Introduction useState Hook useEffect Hook Effect Dependencies and Cleanup useRef Hook useReducer Hook useMemo Hook useCallback Hook Custom Hooks Rules of Hooks
12. React Context API
Context API Introduction createContext useContext Context Provider Reading Context Updating Context Using Multiple Contexts Context API vs Props Context API Best Practices
13. React Routing
Routing Introduction Introduction to React Router Installing React Router BrowserRouter Setup Routes and Route Components Link and NavLink Programmatic Navigation URL Parameters and useParams Nested Routes Not Found Routes Protected Routes
14. API Integration
API Integration Introduction Fetch API Async/Await with API Calls Displaying API Data Loading and Error States Sending POST Requests API Error Handling Using Axios Custom Fetch Hook API Environment Variables
15. State Management
State Management Introduction Global State Prop Drilling Introduction to Redux Redux Core Concepts Redux Toolkit Store and Slices useSelector and useDispatch Async Operations with Redux Toolkit State Management Best Practices
16. React Performance
Performance Introduction Understanding Re-Renders Avoiding Unnecessary Re-Renders React.memo useMemo Optimization useCallback Optimization React Developer Tools and Profiler Lazy Loading Components Code Splitting Optimizing Large Lists Performance Best Practices

Sending POST Requests in React

In this lesson, you will learn how to send data from a React application to an API using the HTTP POST method. You will understand request headers, JSON request bodies, form handling, server responses, and error handling.

1. What Is a POST Request?

An HTTP POST request is commonly used to submit data to a server. For example, a React application may submit a registration form, create a new student record, or send product information to a backend.

With a POST request, the client can include data in the request body. The server processes that data according to the API's rules and returns an HTTP response.

Real-Life Examples

  • Submitting a student registration form.
  • Creating a new course record.
  • Submitting a contact form.
  • Creating an order in an e-commerce application.
Remember: POST is commonly used to create resources or submit data, but its exact behavior depends on the API endpoint.

2. GET vs POST

GET and POST are HTTP methods used for different purposes. GET is generally used to retrieve data, while POST is often used to submit data for processing or resource creation.

  • GET: Requests information from an API.
  • POST: Sends data in the request body.
GET Request
const response = await fetch("/api/students");

const students = await response.json();
POST Request
const response = await fetch("/api/students", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "Samadhan",
        course: "React"
    })
});
The endpoint /api/students is an illustrative URL. Your backend must implement and support that endpoint for the request to work.

3. How a POST Request Works

User Fills React Form
↓
React Collects Form Values
↓
POST Request with JSON Body
↓
Backend Validates and Processes Data
↓
API Returns HTTP Response
↓
React Displays Success or Error

The React component collects the user's input and sends it to the API. The backend receives the request, validates the data, performs the required operation, and returns a response. React then updates its interface based on the result.

4. Understanding the Fetch POST Options

Fetch accepts a URL and an optional configuration object. The configuration object allows you to specify the HTTP method, headers, and request body.

POST Request Structure
fetch("https://api.example.com/students", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "Samadhan",
        course: "React"
    })
});

Explanation

  • method: "POST" tells Fetch to send a POST request.
  • headers contains metadata about the request.
  • Content-Type: application/json tells the server that the request body is JSON.
  • body contains the data being submitted.
  • JSON.stringify() converts a JavaScript object into a JSON string.
Important: When sending JSON, use JSON.stringify(). A plain JavaScript object cannot be used directly as the Fetch request body.

5. Create a React Form

Before sending data, create a form to collect the user's input. In React, controlled inputs use state to keep their values synchronized with the component.

StudentForm.jsx
import { useState } from "react";

function StudentForm() {
    const [name, setName] = useState("");
    const [course, setCourse] = useState("");

    return (
        <form>
            <label>
                Student Name
                <input
                    type="text"
                    value={name}
                    onChange={event => setName(event.target.value)}
                />
            </label>

            <label>
                Course
                <input
                    type="text"
                    value={course}
                    onChange={event => setCourse(event.target.value)}
                />
            </label>

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

export default StudentForm;

Understanding the Form

  • useState("") initializes each input with an empty string.
  • value connects the input to its state value.
  • onChange updates state when the user types.
  • type="submit" makes the button submit the form.
This step only collects form values. The next example adds form submission logic and sends the data to the API.

6. Send Form Data Using a POST Request

The following complete component submits student details to an example endpoint. It prevents the browser's default form submission, sends JSON to the server, and displays a success or error message.

StudentForm.jsx
import { useState } from "react";

function StudentForm() {
    const [name, setName] = useState("");
    const [course, setCourse] = useState("");
    const [message, setMessage] = useState("");
    const [loading, setLoading] = useState(false);

    async function handleSubmit(event) {
        event.preventDefault();

        setMessage("");
        setLoading(true);

        try {
            const response = await fetch(
                "https://jsonplaceholder.typicode.com/posts",
                {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify({
                        title: name,
                        body: course,
                        userId: 1
                    })
                }
            );

            if (!response.ok) {
                throw new Error("Failed to submit data");
            }

            const result = await response.json();

            setMessage(
                `Data submitted successfully. Response ID: ${result.id}`
            );

            setName("");
            setCourse("");
        } catch (error) {
            setMessage(error.message || "Something went wrong");
        } finally {
            setLoading(false);
        }
    }

    return (
        <div>
            <h2>Student Registration</h2>

            <form onSubmit={handleSubmit}>
                <div>
                    <label htmlFor="studentName">Student Name</label>
                    <input
                        id="studentName"
                        type="text"
                        value={name}
                        onChange={event => setName(event.target.value)}
                        required
                    />
                </div>

                <div>
                    <label htmlFor="course">Course</label>
                    <input
                        id="course"
                        type="text"
                        value={course}
                        onChange={event => setCourse(event.target.value)}
                        required
                    />
                </div>

                <button type="submit" disabled={loading}>
                    {loading ? "Submitting..." : "Submit"}
                </button>
            </form>

            {message && <p role="status">{message}</p>}
        </div>
    );
}

export default StudentForm;

Step-by-Step Explanation

  1. handleSubmit runs when the form is submitted.
  2. event.preventDefault() prevents a normal browser form submission and page reload.
  3. setLoading(true) indicates that the request is in progress.
  4. fetch() sends a POST request with JSON data.
  5. response.ok checks whether the server returned a successful HTTP status.
  6. response.json() reads the response body.
  7. setMessage() displays feedback to the user.
  8. finally resets the loading state regardless of whether the request succeeds or fails.
JSONPlaceholder is a testing API. It simulates resource creation and returns a response, but it does not permanently save the submitted record. Replace the endpoint with your own backend API when connecting a real application.

7. Understanding the POST Response

After processing a POST request, an API may return the created resource, an identifier, a status message, or another response defined by the endpoint.

Illustrative JSON Response
{
    "title": "Samadhan",
    "body": "React",
    "userId": 1,
    "id": 101
}

In this example, id represents an identifier returned by the API. The actual response structure depends on the server.

Example UI Message

Data submitted successfully. Response ID: 101

A successful HTTP response does not guarantee that every expected field exists in the response body. Validate the response structure before relying on specific properties.

8. Common Mistakes

  • Forgetting event.preventDefault(): The browser may perform a normal form submission and reload the page.
  • Forgetting JSON.stringify(): Convert the JavaScript object into a JSON string before sending it as a JSON request body.
  • Missing Content-Type: When sending JSON, identify the body format with the appropriate request header.
  • Ignoring HTTP errors: Check response.ok before treating the request as successful.
  • Allowing duplicate submissions: Disable the submit button while the request is running when appropriate.
  • Assuming the data is saved: A test API may simulate a POST response without storing data permanently.
  • Exposing sensitive information: Never place private API secrets or server credentials in frontend code.

9. Practice Tasks

Task 1: Create a Contact Form

Create a React form with name, email, and message fields. Collect the input values using useState.

Task 2: Send a POST Request

Send the contact form data using Fetch, the POST method, a JSON Content-Type header, and JSON.stringify().

Task 3: Show a Loading State

Disable the submit button while the request is in progress and change its text to "Submitting...".

Task 4: Display the Response

Parse the response JSON and display a suitable success message after checking the HTTP status.

Task 5: Handle Errors

Use try/catch/finally to handle request failures and restore the submit button after the operation finishes.

Summary

In this lesson, you learned how POST requests submit data to an API, how to configure Fetch with an HTTP method and headers, how JSON.stringify converts an object into a request body, and how to collect form values using React state. You also learned to prevent default form submission, process API responses, display loading and success messages, and handle errors with try/catch/finally. In the next lesson, you will learn more about handling API errors and building reliable error-handling logic in React.