I have a piece of code that should be rendered based on the condition applied. For example:
isMobile ? <MyComponent> : <div className={styles.myclassStyle}>
....other code goes here....
isMobile ? </MyComponent> : </div>
if isMobile is true, then MyComponent should be selected otherwise the html element
div . Is it possible to do so? Any alternate solution?
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them. This example renders a different greeting depending on the value of isLoggedIn prop.
The answer is NO. It works because, in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false. Therefore, if the condition is true, the element right after " && " will appear in the output. If it is false, React will ignore and skip it.
Logical && Operator Another way to conditionally render a React component is by using the && operator.
you would conditionally render the entire bit of code and you would would have to return it in parenthesis with a single root element. so for instance
{
isMobile ? (
<MyComponent>
// this code runs if isMobile === true
// ... code for MyComponent
</MyComponent>
) : (
<div className={styles.myclassStyle}>
// this code runs of isMobile === false
// ... code for the div goes here
</div>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With