Kev Lozano
Kev Lozano

Reputation: 81

How to render several components with a ternary operator in JSX/React?

Sorry if any of my terminology is wrong, I'm not sure what this things are called. I've seen some people deconstruct components in this way:

// instead of
return (
  <div>
    <Component />
  </div>
)

// they do this
const component = (
  <div>
    <Component />
  </div>
)

return (
  {component}
)

I like it because it keeps code more organized, I don't know exactly what this method is called which makes it a little hard to look for answers somewhere else. My question is how do I put several components inside a ternary operator in his way? something like this:

const component = (
  <div>
    <Component />
  </div>
)
const otherComponent = (
  <div>
    <OtherComponent />
  </div>
)

return (
  {this.state.conditional ? component otherComponent : ""}
)

If I try this the app fails to compile and the error is: Parsing Error: unexpected token, expected "}".

I've tried several variations like wrapping the variables in curly braces, commas, or something else but nothing seems to work. I'm sure I'm missing something key here.

Upvotes: 2

Views: 2889

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14375

You could just wrap them in a fragment like this and it should work:

{this.state.conditional ? <>{component} {otherComponent}</> : ""}

You're having an issue because you're basically trying to return two things from the ternary. It'd be like a function doing () => {return a; return b;}. Even if it did work, you'd get an error for rendering more than one react element.

By wrapping it in a single tag like a fragment, you're telling it to return a single element that's composed of two values.

Upvotes: 5

Related Questions