How to render a boolean value in JSX in React

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

Render a boolean value in JSX in React #

Use the String() function to render a boolean value in JSX in React, e.g. <h2>{String(bool1)}</h2>. By default boolean values don't render anything in React, so we have to convert the value to a string in order to render it.

App.js
export default function App() { const bool1 = true; const bool2 = false; return ( <div> <h2>bool1: {String(bool1)}</h2> <hr /> <h2>bool2: {String(bool2)}</h2> </div> ); }

react show boolean value

We have to convert boolean values to a string in order to show them in our JSX code.

Booleans, null, undefined are ignored. They simply don't render.

The following JSX expressions all render nothing.

App.js
<div /> <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>

Alternatively, you can use the toString() method on a boolean to convert it to a string.

App.js
export default function App() { const bool1 = true; const bool2 = false; return ( <div> <h2>bool1: {bool1.toString()}</h2> <hr /> <h2>bool2: {bool2.toString()}</h2> </div> ); }

The Boolean.toString method returns the string representation of the boolean.

Another commonly used approach is to convert the boolean to a string by using a template literal.

App.js
export default function App() { const bool1 = true; const bool2 = false; return ( <div> <h2>{`bool1: ${bool1}`}</h2> <hr /> <h2>{`bool2: ${bool2}`}</h2> </div> ); }

We used a template literal to interpolate a boolean variable in a string.

Note that the string is enclosed in backticks ``, not in single quotes.

The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.

By default, the template literal concatenates the parts into a string.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.