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

1. Introduction to Forms

Forms are used to collect information from users. Examples include login forms, registration forms, contact forms, and feedback forms.

In React, we can create forms using HTML form elements such as input, textarea, select, and button. React helps us manage the input values and respond when a user submits a form.

Remember: React forms allow users to enter information that a component can manage, validate, and process.

2. Creating a Basic Form in React

A basic React form can contain labels, input fields, and a submit button. JSX is used to describe the form elements that React displays on the page.

Example

function ContactForm() {
    return (
        <form>
            <label htmlFor="name">Name:</label>

            <input
                type="text"
                id="name"
                name="name"
            />

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

export default ContactForm;

Expected Output

Contact Form

The form displays a text input and a submit button. The example demonstrates the structure of a form; it does not yet process or store the entered value.

3. Common Form Elements

React supports standard HTML form elements. Each element is used to collect a particular type of information.

Element Purpose Example
input Accepts user input. Name or email
textarea Accepts multiline text. Comments
select Provides a list of options. Select a course
button Allows users to perform an action. Submit
label Describes a form field. Email Address
Important: Use a label with its corresponding input to make the purpose of each form field clear.

4. Understanding Form Structure

A form groups related input fields and provides a way for users to submit the information they enter.

User Opens the Form The form is displayed in the component.
↓
User Enters Information Name, email, and other form values
↓
User Submits the Form The submit action is triggered.
↓
Process Form Data Validate and process the entered information.

This is the general workflow of a form. The exact processing depends on how the React component is implemented.

5. Understanding Form Input Values

An input element allows a user to enter information. In React, we can use state to store the input value and update it whenever the user types.

Example: Managing a Name Field

import { useState } from "react";

function NameForm() {
    const [name, setName] = useState("");

    function handleChange(event) {
        setName(event.target.value);
    }

    return (
        <div>
            <label htmlFor="studentName">
                Student Name:
            </label>

            <input
                id="studentName"
                type="text"
                value={name}
                onChange={handleChange}
            />

            <p>Entered Name: {name}</p>
        </div>
    );
}

export default NameForm;

Expected Output

Entered Name: Rahul

The useState hook stores the name, and the onChange handler updates the state when the input value changes. React then displays the updated value.

6. Understanding Form Submission

Form submission occurs when a user submits the form, commonly by clicking a submit button. React applications can handle submission with an onSubmit event handler.

Example

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

        console.log("Form submitted");
    }

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="feedback">
                Feedback:
            </label>

            <input
                id="feedback"
                name="feedback"
                type="text"
            />

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

export default FeedbackForm;

Expected Result

When the form is submitted in the running React application, the browser's default form submission is prevented and "Form submitted" is written to the console.

Remember: event.preventDefault() prevents the browser's default form submission behavior. It does not automatically save the form data.

7. React Forms and State

State is useful when a component needs to remember the values entered by a user. A controlled input receives its value from React state and updates that state through an event handler.

Example

import { useState } from "react";

function EmailForm() {
    const [email, setEmail] = useState("");

    return (
        <div>
            <label htmlFor="email">Email:</label>

            <input
                id="email"
                type="email"
                value={email}
                onChange={(event) =>
                    setEmail(event.target.value)
                }
            />

            <p>Email: {email}</p>
        </div>
    );
}

export default EmailForm;

Expected Output

Email: student@example.com

The email state stores the current input value. When the user types, the onChange handler updates the state and React displays the new value.

8. Common Mistakes

Mistake 1: Using an Incorrect Label Association

<label>Email</label>
<input type="email" id="email" />

The label is not explicitly connected to the input. Associating them improves usability and accessibility.

Correct Code

<label htmlFor="email">Email</label>
<input type="email" id="email" />

Mistake 2: Forgetting to Update State

<input
    value={name}
    onChange={() => {}}
/>

The handler does not update the name state, so the controlled input cannot reflect new values entered by the user.

Correct Code

<input
    value={name}
    onChange={(event) =>
        setName(event.target.value)
    }
/>

Mistake 3: Forgetting to Prevent Default Submission

function handleSubmit(event) {
    console.log("Form submitted");
}

If you want to handle the form submission in React without the browser's default submission behavior, call preventDefault() in the submit handler.

Correct Code

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

    console.log("Form submitted");
}

9. Practice Tasks

Complete these tasks to practise creating forms in React.

Task 1: Create a form containing a name input and a submit button.
Task 2: Create a contact form containing name, email, and message fields.
Task 3: Use useState to store the value entered into a text input.
Task 4: Create a form with an onSubmit handler that prevents the browser's default submission behavior.
Task 5: Create an email input and display its current value below the input field.

Summary

Forms in React collect information from users through elements such as input, textarea, select, and button. React components can use state to store input values and update them when users type. Event handlers can respond to changes and form submissions, while event.preventDefault() prevents the browser's default submission behavior when needed. These fundamentals provide the foundation for controlled components, input handling, form validation, and form submission.