简体   繁体   中英

Conditionally render multiple elements inside a react fragment

I have a function that takes a few booleans and should render an html element for each boolean if it's true. This is what I want to do:

function renderThis (first, second, third) {
  if (!(first || second || third)) {
    return <span>each input is false</span>
  }
  return (
  //README: This part below doesn't work. How can I conditionally render these span tags below?
    <React.Fragment>
      {
        first
          ? <span>First is true</span>
          : null
        second
          ? <span>Second is true</span>
          : null
        third
          ? <span>Third is true</span>
          : null
        credit
      }
    </React.Fragment>
  )
}

The fragment doesn't work now. I can conditionally render one element (for instance, I can render first if I remove the subsequent second and third variables and their associated code), but not all three. How can I conditionally render all three variables here?

Turn your returned elements into an array . You can't return adjacent jsx

 <React.Fragment>
      {
        [
           true ? <span key='1'>First is true</span>: null,
           true ? <span key='2'>Second is true</span>: null,
           false ? <span key='3'>Third is true</span>: null
        ]

      }
    </React.Fragment>

If you are returning just the array you don't need Fragment

return [
   true ? <span>First is true</span>: null,
   true ? <span>Second is true</span>: null,
   false ? <span>Third is true</span>: null
]

Also, you can't return adjacent jsx from the same statement, but you can return adjacent unary statements

return(
    <>
        {true ? <span /> : null} 
        {false ? <span /> : null}
    </>
)

编辑沉思-http-zx5p9

If you want to render all three spans based on condition of each one you could do something like this:

function renderThis(first, second, third) {
  if (!(first || second || third)) {
    return <span>each input is false</span>;
  }
  return (
    //README: This part below doesn't work. How can I conditionally render these span tags below?
    <React.Fragment>
      {first && <span>First is true</span>}
      {second && <span>Second is true</span>}
      {third && <span>Third is true</span>}
    </React.Fragment>
  );
}

The Array approach seems overly complicated to me. Why not just this?

<React.Fragment>
   {true  && <span>First is true</span>}
   {true  && <span>Second is true</span>}
   {false && <span>Third is true</span>}
</React.Fragment>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM