Skip to content

Conditional Rendering

In React, there are several ways to handle conditional renderings.

1. Using if Statements

js
function Theme({ mode }) {
	if (mode === 'dark') {
		return <div>Dark Mode</div>
	} else {
		return <div>Light Mode></div>
	}
}

2. Using Ternary Operators

A more concise way of conditionally rendering the elements:

js
function Theme({ mode }) {
	return (
		<div>{mode === 'dark' ? 'Dark Mode' : 'Light Mode'}</div>
	)
}

3. Using Logical && Operator

The logical && operator is useful to render when a condition is true.

js
function ErrorMessage({ status }) {
	return (
		<div>
			<h1>Status</h1>
			{status === 'error' && <div>An Error Occurred</div>}
		</div>
	)
}

4. Using switch Statements

js
function Status({ status }) {
	switch (status) {
		case 'loading':
			return <p>Loading...</p>;
		case 'error':
			return <p>Error occurred!</p>;
		case 'success':
			return <p>Data loaded successfully!</p>;
		default:
			return null;
	}
}