if / else Statements
if / else Statements
An if/else statement is the most straightforward way to apply conditional logic. In React, you place the if/else outside the JSX return statement to decide which element or JSX block to render.
The if/else statement cannot be used inside JSX curly braces {} because it is a statement, not an expression. You must use it before the return keyword, or use an expression-based alternative inside JSX.
Key Rule: JSX curly braces{}only accept expressions (values that produce a result), not statements (likeif,for, orswitch). If/else must live outside the return block.
Basic if / else
import { useState } from 'react'; function Dashboard() { const [isLoggedIn, setIsLoggedIn] = useState(false); // if/else OUTSIDE the return — this is correct let content; if (isLoggedIn) { content = ( <div> <h2>Welcome back!</h2> <p>You have 3 courses in progress.</p> </div> ); } else { content = ( <div> <h2>Please log in</h2> <p>Access your 7Scribes courses.</p> </div> ); } return ( <div> {content} <button onClick={() => setIsLoggedIn(!isLoggedIn)}> {isLoggedIn ? 'Log Out' : 'Log In'} </button> </div> ); }
Early Return Pattern
A very popular pattern is to return early from a component for special cases (loading, error, empty state) before reaching the main JSX. This keeps the main JSX clean and readable.
function CourseList({ loading, error, courses }) { // Early return for loading state if (loading) { return <p>Loading courses...</p>; } // Early return for error state if (error) { return <p style={{ color: 'red' }}>Error: {error}</p>; } // Early return for empty state if (!courses || courses.length === 0) { return <p>No courses available yet.</p>; } // Main render — all edge cases handled above return ( <ul> {courses.map((c) => ( <li key={c.id}>{c.title}</li> ))} </ul> ); }
if / else if / else
function UserRoleView({ role }) { let view; if (role === 'admin') { view = <AdminDashboard />; } else if (role === 'instructor') { view = <InstructorPanel />; } else if (role === 'student') { view = <StudentHome />; } else { view = <GuestLanding />; } return <main>{view}</main>; }
