If-Else and Switch in React JSX

In this small tutorial I would like to describe you 4 ways of performing conditional rendering in JSX. Maybe you already know some of them, maybe not, anyway hope it will be useful for you.

In all the below examples let’s assume that you have headingLevel variable which can be h1, h2, h3 etc and depending on its value we have to print some kind of text in an appropriate HTML tag.

Ternary operator

<div>
	{
		'h1' === headingLevel
		? <h1>Hello world!</h1>
		: <p>Welcome to WordPress. This is your first post.</p>
	}
</div>

This shorthand conditional statement could be extended even more to multiple if-else statements.

<div>
	{
		'h1' === headingLevel
		? <h1>Hello world!</h1>
		: 'h2' === headingLevel
		? <h2>Hello world!</h2>
		: <p>Welcome to WordPress. This is your first post.</p>
	}
</div>

Of course creating this unlimited amount of if-else shorthand statements probably isn’t a good idea, so that’s why we have to think towards using switch instead.

Regular if, else and else if

I decided to start with a ternary operator first, because it looks more interesting and handy but I am sure you have to know how to perform a “boring” conditioning as well.

Let’s take a look at the same example we did above.

<div>
	{
		if( 'h1' === headingLevel ) {
			return( 
				<h1>Hello world!</h1> 
			)
		} else {
			return( 
				<p>Welcome to WordPress. This is your first post.</p>
			)
		}
	}
</div>

And the second example as well:

<div>
	{
		if( 'h1' === headingLevel ) {
			return( 
				<h1>Hello world!</h1> 
			)
		} else if( 'h2' === headingLevel ) {
			return( 
				<h2>Hello world!</h2> 
			)	 
		} else {
			return(
				<p>Welcome to WordPress. This is your first post.</p>
			)
		}
	}
</div>

And yes, it is quite obvious, that the last example is better with switch.

Logical operator

If we take the first example from here and assume that we do not need “else” part, then our condition can be simplified even more.

<div>
	{
		'h1' === headingLevel && <h1>Hello world!</h1>
	}
</div>

There is also possible to perform conditional rendering with OR ||, which means that the first available component will returned.

Switch

Last but not least, switch operator, that allows to bypass complex conditional if-else rendering.

<div>
	{
		switch( headingLevel ) {
			case 'h1' : {
				return( 
					<h1>Hello world!</h1> 
				);
				break
			}
			case 'h2' : {
				return(
					<h2>Hello world!</h2> 
				)
				break
			}
			default : {
				return( 
					<h1>Hello world!</h1> 
				)
				break
			}
		}
	}
</div>

There is also a tutorial about creating loops in React JSX on my blog.

Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X