We use javascript for conditional rendering
? :)function Greeting({ isLoggedIn }) {
return <div>{isLoggedIn ? <UserDashboard /> : <LoginButton />}</div>;
}&&)AND logic.function Mailbox({ unreadMessages }) {
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 && (
<h2>You have {unreadMessages.length} unread messages.</h2>
)}
</div>
);
}nullIf we want a component to hide itself based on a prop, return null.
function Banner({ show }) {
if (!show) {
return null; // Renders nothing
}
return <div className="banner">Warning!</div>;
}To render a list of items, we use the JavaScript array method .map(). We transform an array of data into an array of JSX elements.
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
];
function UserList() {
return (
<ul>
{users.map((user) => (
// Every item in a list MUST have a unique 'key' prop
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}When we render a list, React needs to know which items changed, were added, or were removed.
Index as Key Anti-PatternAvoid doing this: users.map((user, index) => <li key={index}>...</li>)
index if the list is completely static (never changes, never filters, never reorders). Otherwise, use a unique ID (like database ID).| Concept | Definition | When to use |
|---|---|---|
Ternary (? :) | cond ? A : B | When rendering one of two options. |
Short-Circuit (&&) | cond && A | When showing/hiding a single option. |
.map() | Array method. | To loop through data and return JSX. |
key Prop | A unique string/number. | Required for every item in a list. |
| Index as Key | Using array index. | Avoid unless list is static. |
count && <h1>Messages</h1> and count is 0, what will appear on the screen? A hidden element or the number 0?The number 0 will appear on the screen.
Why: This is a classic JavaScript "gotcha." The && operator returns the value of the first falsy operand it finds. Since 0 is falsy, the expression short-circuits and returns 0.
React's Behavior: React ignores false, null, and undefined (renders nothing), but it renders numbers. Since the expression returned 0, React prints "0" on the UI.
The Fix: Always force the condition to be a real boolean.
count > 0 && <h1>Messages</h1> (Recommended)key?React will throw a warning in the console (Encountered two children with the same key...) and we may experience rendering bugs.
index as a key for a footer navigation menu (e.g., "About", "Contact", "Terms") that never changes?Yes, it is perfectly fine.