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

Conditional CSS Classes in React

Learn how to apply different CSS classes to React elements based on conditions using JSX and className.

1. What Are Conditional CSS Classes?

Conditional CSS classes allow us to apply different CSS classes to an element depending on a condition. For example, a React application can display a success message in green and an error message in red.

In React, we use className instead of the HTML class attribute when assigning CSS classes in JSX. JavaScript expressions can be used inside curly braces to choose a class dynamically.

Remember: React uses className in JSX. A condition can determine which CSS class is assigned to an element.

2. Syntax of Conditional CSS Classes

The basic syntax uses the ternary operator:

className={'{condition ? "classA" : "classB"}'}
Message.jsx JSX
function Message() {
    const isSuccess = true;

    return (
        <p className={isSuccess ? "success" : "error"}>
            Operation completed!
        </p>
    );
}

export default Message;

Code Explanation

  • isSuccess stores the condition.
  • If the condition is true, the success class is applied.
  • If the condition is false, the error class is applied.
  • The CSS class determines the element's appearance.

CSS

Message.css CSS
.success {
    color: green;
    font-weight: bold;
}

.error {
    color: red;
    font-weight: bold;
}

Expected Output

Browser Output

Operation completed!

3. Flow Diagram of Conditional Classes

The condition determines which class name React assigns to the element.

React Component
↓
Check the condition
Condition: true
↓
Apply success class
↓
Display green text
Condition: false
↓
Apply error class
↓
Display red text

4. Example: Active and Inactive Status

A dashboard can use conditional classes to show whether a user is active or inactive.

UserStatus.jsx JSX
function UserStatus() {
    const isActive = true;

    return (
        <div>
            <h2>User Status</h2>

            <p className={isActive ? "active" : "inactive"}>
                {isActive ? "Active User" : "Inactive User"}
            </p>
        </div>
    );
}

export default UserStatus;

CSS

UserStatus.css CSS
.active {
    color: green;
    font-weight: bold;
}

.inactive {
    color: red;
    font-weight: bold;
}

Expected Output

Browser Output

User Status

Active User

Try it: Change isActive to false. The message will become "Inactive User" and use the inactive CSS class.

5. Conditional Classes Using Logical AND

The logical AND operator can add a CSS class only when a condition is true. A common example is highlighting an item that is selected.

Course.jsx JSX
function Course() {
    const isSelected = true;

    return (
        <div
            className={`course-card ${isSelected ? "selected" : ""}`}
        >
            <h2>React Development</h2>
            <p>Learn components and JSX.</p>
        </div>
    );
}

export default Course;

CSS

Course.css CSS
.course-card {
    padding: 16px;
    border: 1px solid #cccccc;
    border-radius: 8px;
}

.course-card.selected {
    border: 2px solid green;
    background-color: #f0fff0;
}

Expected Output

Browser Output

React Development

Learn components and JSX.

When isSelected is true, the selected class is added. When it is false, the base course-card class remains.

6. Multiple Conditional Classes

A component can apply different classes based on more than one condition.

Notification.jsx JSX
function Notification() {
    const isSuccess = true;
    const isImportant = true;

    const classNames = [
        "notification",
        isSuccess ? "success" : "error",
        isImportant ? "important" : ""
    ].filter(Boolean).join(" ");

    return (
        <p className={classNames}>
            Your registration was completed!
        </p>
    );
}

export default Notification;

CSS

Notification.css CSS
.notification {
    padding: 12px;
    border-radius: 6px;
}

.success {
    color: green;
}

.error {
    color: red;
}

.important {
    font-weight: bold;
    border: 2px solid currentColor;
}

Expected Output

Browser Output

Your registration was completed!

Explanation: The array stores the base class and the conditional classes. filter(Boolean) removes empty entries, and join(" ") combines the remaining class names.

7. Conditional Classes with Props

A reusable React component can receive a prop and choose its CSS class based on that prop.

StatusBadge.jsx JSX
function StatusBadge({ status }) {
    return (
        <span className={status === "success" ? "badge-success" : "badge-error"}>
            {status === "success" ? "Completed" : "Failed"}
        </span>
    );
}

function App() {
    return (
        <div>
            <StatusBadge status="success" />
            <StatusBadge status="error" />
        </div>
    );
}

export default App;

CSS

StatusBadge.css CSS
.badge-success {
    color: green;
    background: #e8f8ec;
    padding: 6px 12px;
    border-radius: 5px;
}

.badge-error {
    color: red;
    background: #fdecec;
    padding: 6px 12px;
    border-radius: 5px;
}

Expected Output

Browser Output
Completed Failed

8. Common Mistakes to Avoid

1. Using class instead of className

Incorrect in JSX:

<p class="success">Completed</p>

Correct:

<p className="success">Completed</p>

2. Forgetting to separate class names

When combining class names in a string, separate them with spaces. Otherwise, the browser treats the combined text as a single class name.

className={`card ${isSelected ? "selected" : ""}`}

9. Practice Tasks

Complete these exercises using React:

  1. Create a message that uses a green class for success and a red class for failure.
  2. Create an active/inactive user status component.
  3. Highlight a selected course card using a conditional class.
  4. Create a notification component that combines two conditional CSS classes.
  5. Create a reusable status badge that receives its status through props.
Practice Tip: Test both true and false values to verify that the correct CSS class is applied.

Summary

Conditional CSS classes in React allow elements to receive different styles based on conditions. The className attribute is used in JSX to assign CSS classes. The ternary operator can choose between class names, while template literals can combine multiple classes. Props can also determine which class a reusable component applies. Conditional classes are useful for status messages, selected cards, notifications and other dynamic UI elements.