Using Javascript inside JSX

Lesson link:
https://www.codecademy.com/paths/build-web-apps-with-react/tracks/bwa-intro-to-react/modules/react-101-jsx-u/lessons/react-jsx-advanced/exercises/jsx-pi-20-digits

Just playing around with JSX and I’m confused why this doesn’t render the text, ‘true’ on the webpage?

const math = <h1>{2 + 3 === 2 + 3}</h1>

ReactDOM.render(math, document.getElementById('app'))

Must be due to the fact that true is a boolean type and therefore not rendered as a string.
This should do the trick:

const math = <h1>{ 2 + 3 === 2 + 3 && 'true' }</h1>

What’s happening here? Not understanding what the ‘true’ string is for?

image

1 Like

That’s a common way of conditional rendering in React.

If ‘2 + 3 === 2 + 3’ is true render ‘true’

You can render whatever string like { 2 + 3 === 2 + 3 && 'this is strictly equal' }

Ohh is this just short circuit evaluation but with && instead of || ?

&& means AND and || means OR.
In React it’s common to use shorthand syntax like

{ 1===1 && 'equal' }

if 1===1 render equal, if not: nothing.

{ (1===2  || 1===1) && 'one of the conditions is equal' }

if 1===2 or 1===1 is true render ‘one of the conditions is equal’, if none is true: nothing.

{ 1===1 ? 'true' : 'false' }

if 1===1 is true render ‘true’, if not render ‘false’.