MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Conditional Rendering with If-Else and Ternary Operators0%
Study Materials
React.js for BeginnersProgress 0%
1.1Why React and Single-Page Architecture1.2Setting Up Modern React with Vite1.3React Project Directory Structure and Entry Points1.4Virtual DOM and React Render Cycle Explained
7.1Conditional Rendering with If-Else and Ternary Operators7.2Logical AND Operator for Inline Rendering7.3Preventing Component Rendering with Null7.4Managing Loading, Error, and Empty States
HomeTutorialsReact.js for BeginnersConditional Rendering with If-Else and Ternary Operators
Logical AND Operator for Inline Rendering

Conditional Rendering with If-Else and Ternary Operators

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. What is Conditional Rendering?

In real-world web applications, user interfaces frequently need to display different components or markup depending on specific conditions:

  • Showing a "Login" button for guests vs a "Profile" dropdown for authenticated users
  • Showing a spinner while data is loading vs the actual data when loaded
  • Showing an error banner when a form submission fails
  • Showing an empty state when a shopping cart has 0 items

In React, conditional rendering works the exact same way conditions work in JavaScript: using standard JavaScript control flow structures such as if/else statements, ternary operators (? :), and logical operators.

2. Method 1: Early Return with if/else

When a condition dictates that a completely different view should be rendered, using standard if statements with early returns is clean and readable:

1import React from 'react';
2 
3export default function UserDashboard({ user, isLoading, error }) {
4 // 1. Loading state early return
5 if (isLoading) {
6 return <div className="spinner">Loading your dashboard...</div>;
7 }
8 
9 // 2. Error state early return
10 if (error) {
11 return <div className="error-alert">Error: {error.message}</div>;
12 }
13 
14 // 3. Unauthenticated state early return
15 if (!user) {
16 return (
17 <div className="guest-view">
18 <h2>Please Sign In</h2>
19 <button>Login to Continue</button>
20 </div>
21 );
22 }
23 
24 // 4. Primary view (all checks passed)
25 return (
26 <div className="dashboard-view">
27 <h2>Welcome back, {user.name}!</h2>
28 <p>Enrolled Courses: {user.enrolledCount}</p>
29 </div>
30 );
31}

Note: Make sure any React Hooks (like useState or useEffect) are declared before any early returns to obey the Rules of Hooks!

3. Method 2: The Ternary Operator (condition ? trueVal : falseVal)

Because if statements are statements (not expressions), they cannot be used directly inside JSX markup. When you want to conditionally render one of two elements inline, the ternary operator is the tool of choice:

1import React, { useState } from 'react';
2 
3export default function MembershipCard({ isProMember }) {
4 return (
5 <div className="card">
6 <h3>MSK Learning Portal</h3>
7
8 {/* Inline ternary conditional rendering */}
9 {isProMember ? (
10 <div className="pro-badge">
11 <span className="star">★</span>
12 <span>Pro Subscriber: Unlimited Lab Access</span>
13 </div>
14 ) : (
15 <div className="free-tier">
16 <span>Standard Member: 3 Free Lessons Remaining</span>
17 <button className="upgrade-btn">Upgrade to Pro</button>
18 </div>
19 )}
20 </div>
21 );
22}

4. Conditional Attribute and Class Assignment

Ternary operators are also invaluable for conditionally applying classes, styles, and attribute values:

1<button
2 className={`btn ${isActive ? 'btn-primary' : 'btn-outline'}`}
3 disabled={isLoading}
4 aria-expanded={isOpen ? 'true' : 'false'}
5>
6 {isLoading ? 'Saving...' : 'Save Changes'}
7</button>

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
Why can't you place an if statement directly inside JSX curly braces {}?
Question 2
What is the primary advantage of using early return statements for conditional rendering?
Question 3
What rule must be respected when combining React Hooks with early returns?
Question 4
Which operator is used for inline conditional rendering when you want to choose between two alternate elements?
Question 5
What is rendered if a ternary condition evaluates to condition ? null : <Button /> and the condition is true?
Next Lesson

Logical AND Operator for Inline Rendering

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Filtering and Sorting List Data DynamicallyLogical AND Operator for Inline Rendering

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Beginners with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext