Question
Can I set my if statement equal to a function, then inject the function into a JSX expression?
Answer
We can! Because a JavaScript function is an expression and not a statement, we can inject a function that performs conditional logic into a JSX expression.
For example:
import React from 'react';
import ReactDOM from 'react-dom';
function myConditional () {
const randNum = Math.floor(Math.random() * 11); // sets randNum to random integer from 0 to 10
if(randNum >= 5){
return 'Random number is greater than or equal to 5!'
} else {
return 'Random number is less than 5!';
}
}
const heading = (
<h1>{myConditional()}</h1> // the JavaScript expression, the myConditional function, can be injected into a JSX expression and will evaluate to either 'Random number is greater than or equal to 5!' or 'Random number is less than 5!' on page load
);
ReactDOM.render(heading, document.getElementById('app'));