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 Input Fields

Input fields allow users to enter information into a form. Examples include student names, email addresses, passwords, phone numbers, and ages.

In React, input values can be managed using state. The onChange event handler responds when the user changes an input value, and the value prop connects the input to React state.

Remember: A controlled input commonly uses value, onChange, and the useState hook.

2. Handling a Text Input

A text input accepts text from the user. We can store the entered text in a state variable and display it on the page.

Example

import { useState } from "react";

function StudentName() {
    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>Student Name: {name}</p>
        </div>
    );
}

export default StudentName;

Expected Output

Student Name: Samadhan Samiksha

When the user types a name, handleChange reads the new value from event.target.value and updates the name state. React then displays the updated name.

3. Handling an Email Input

An email input is used to collect an email address. The type="email" attribute provides browser-level email format checking when the form is submitted.

Example

import { useState } from "react";

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

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

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

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

export default EmailInput;

Expected Output

Email: samadhan@example.com

Important: The email input type does not replace complete form validation. Applications may also need additional validation rules.

4. Handling a Password Input

A password input accepts confidential text and hides the characters visually. React can manage its value using state in the same way as other controlled inputs.

Example

import { useState } from "react";

function PasswordInput() {
    const [password, setPassword] = useState("");

    return (
        <div>
            <label htmlFor="password">Password:</label>

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

            <p>Password length: {password.length}</p>
        </div>
    );
}

export default PasswordInput;

Expected Output

Password length: 9

The password input hides the characters on screen. This example displays only the number of characters, not the password itself.

Security note: Never display or log actual passwords unnecessarily. Password handling and authentication should be implemented securely on the server as well.

5. Handling a Number Input

A number input allows users to enter numeric values. The input's event.target.value is still returned as a string, so convert it when a numeric value is needed.

Example

import { useState } from "react";

function StudentAge() {
    const [age, setAge] = useState("");

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

    return (
        <div>
            <label htmlFor="age">Age:</label>

            <input
                id="age"
                type="number"
                value={age}
                onChange={handleChange}
            />

            <p>Age: {age}</p>
            <p>Next Year: {Number(age || 0) + 1}</p>
        </div>
    );
}

export default StudentAge;

Expected Output

Age: 20

Next Year: 21

The age is stored as the input string. Number() converts it to a number for the calculation. The example uses zero when the field is empty.

6. Handling Multiple Input Fields

A form can contain multiple input fields. We can store their values in a single state object and update the appropriate property using each input's name attribute.

Example: Student Details

import { useState } from "react";

function StudentDetails() {
    const [student, setStudent] = useState({
        name: "Samadhan Samiksha",
        email: "",
        age: ""
    });

    function handleChange(event) {
        const { name, value } = event.target;

        setStudent((previousStudent) => ({
            ...previousStudent,
            [name]: value
        }));
    }

    return (
        <div>
            <label htmlFor="name">Name:</label>
            <input
                id="name"
                name="name"
                value={student.name}
                onChange={handleChange}
            />

            <label htmlFor="email">Email:</label>
            <input
                id="email"
                name="email"
                type="email"
                value={student.email}
                onChange={handleChange}
            />

            <label htmlFor="age">Age:</label>
            <input
                id="age"
                name="age"
                type="number"
                value={student.age}
                onChange={handleChange}
            />

            <p>Name: {student.name}</p>
            <p>Email: {student.email}</p>
            <p>Age: {student.age}</p>
        </div>
    );
}

export default StudentDetails;

Expected Output

Name: Samadhan Samiksha

Email: samadhan@example.com

Age: 20

The name attribute identifies the state property to update. The spread operator preserves the other student details when one field changes.

Remember: Use the same property names in the state object and the corresponding input name attributes.

7. Handling Input Changes with Events

The onChange event handler receives an event object. The event.target property refers to the input that triggered the event.

Example

function handleChange(event) {
    const inputName = event.target.name;
    const inputValue = event.target.value;

    console.log(inputName, inputValue);
}
Property Purpose
event.target Identifies the input element that triggered the event.
event.target.value Reads the current input value.
event.target.name Identifies the input field by its name attribute.
event.target.type Reads the input element's type.

8. Common Mistakes

Mistake 1: Forgetting the onChange Handler

<input value={name} />

The input is controlled by the name state, but there is no handler to update that state when the user types.

Correct Code

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

Mistake 2: Forgetting the name Attribute

<input
    value={student.email}
    onChange={handleChange}
/>

If a shared handler uses event.target.name to identify the property, the input needs the correct name attribute.

Correct Code

<input
    name="email"
    value={student.email}
    onChange={handleChange}
/>

Mistake 3: Treating Number Input Values as Numbers

const [age, setAge] = useState("");

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

Input values are strings by default, including values read from number inputs. Convert the value when a numeric calculation is required.

Correct Calculation

const nextYear = Number(age || 0) + 1;

9. Practice Tasks

Complete these tasks to practise handling input fields.

Task 1: Create a text input for a student's name and display the entered name below it.
Task 2: Create an email input and display the current email value.
Task 3: Create a password input and display only its character count.
Task 4: Create a number input for age and display the age after adding one year.
Task 5: Create a CIIT Training Institute student details form using the name Samadhan Samiksha, email, and age fields. Manage all three values using one state object.

Summary

Handling input fields in React involves connecting input values to state and updating them through onChange event handlers. Text, email, password, and number inputs can all be managed as controlled components. Multiple fields can share a state object, with each input's name attribute identifying the property to update. Input values are strings by default, so numeric conversion is required when performing calculations. These techniques provide a foundation for creating student registration and course enquiry forms at CIIT Training Institute.