Last updated: Apr 7, 2024
Reading time·2 min
Use the String()
function to render a boolean value in JSX in React.
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.
export default function App() { const bool1 = true; const bool2 = false; return ( <div> <h2>bool1: {String(bool1)}</h2> <hr /> <h2>bool2: {String(bool2)}</h2> <hr /> <h2>bobbyhadz.com</h2> </div> ); }
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.
<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.
export default function App() { const bool1 = true; const bool2 = false; return ( <div> <h2>bool1: {bool1.toString()}</h2> <hr /> <h2>bool2: {bool2.toString()}</h2> <hr /> <h2>bobbyhadz.com</h2> </div> ); }
The Boolean.toString method returns the string representation of the boolean.
I've also written a tutorial on how to toggle a boolean state in React.
Another commonly used approach is to convert the boolean to a string by using a template literal.
export default function App() { const bool1 = true; const bool2 = false; return ( <div> <h2>{`bool1: ${bool1}`}</h2> <hr /> <h2>{`bool2: ${bool2}`}</h2> <hr /> <h2>bobbyhadz.com</h2> </div> ); }
We used a template literal to interpolate a boolean variable in a string.
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.
You can also render boolean values in JSX using the JSON.stringify()
method.
export default function App() { const bool1 = true; const bool2 = false; return ( <div> <h2>bool1: {JSON.stringify(bool1)}</h2> <hr /> <h2>bool2: {JSON.stringify(bool2)}</h2> <hr /> <h2>bobbyhadz.com</h2> </div> ); }
The JSON.stringify() method converts a JavaScript value to a JSON string.
Whichever approach you pick, you have to convert the boolean value to a string in order to render it in your JSX code.