Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally render a DIV and REACT component for OPENING and CLOSING tags?

Tags:

html

css

reactjs

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?

like image 244
Eid Avatar asked Jan 16 '20 05:01

Eid


People also ask

How do you conditionally render a div in React?

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.

Should you use ternary or && operator to conditionally render React components?

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.

Which operator can be used to conditionally render a React component?

Logical && Operator Another way to conditionally render a React component is by using the && operator.


Video Answer


1 Answers

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>
  )
}
like image 71
Michael Cacciano Avatar answered Oct 16 '22 07:10

Michael Cacciano