2

I am using ternary operator and I need to render a component. Here is what I have tried:

{count: item.count ? item.count + <Chip/> : '❂'}

{count: item.count ? item.count + `${<Chip/>}` : '❂'}

{count: item.count ? item.count + (<Chip/>) : '❂'}

Instead of rendering the component, I get [object Object]

1
  • 1
    why are you adding item.count with Chip component? Commented Aug 21, 2020 at 14:04

4 Answers 4

3

You can make use of React.Fragment

{count: item.count ? <React.Fragment>{item.count}<Chip/></React.Fragment> : '❂'}

The reason it doesn't work in your case is because you are trying to concatenate values which essentially does string conversion of component which is the not the same as a rendered component

Sign up to request clarification or add additional context in comments.

Comments

2

Or just wrap it in a <div /> element. JSX should always be wrapped in one root tag. Fragment is also an option, as said above.

Comments

1

It looks like you want to render a Chip component or depending on the item.count.

I would suggest using modern React.Fragment, like this:

{item.count ? <>
  <Chip />
  :
  <span>❂</span>
</>}

(I wrapped ❂ in a span purely for clarity)

If you want to display the count first, try this:

{item.count ? <>
  <>
    {item.count}<Chip />
  </>
  :
  <span>❂</span>
</>}

If you want to render Chip one per item.count, then use a loop in the first part.

Comments

0

I am guessing that by using + you want to display both the item.count number and the Chip component. But I think that by using + javascript will call toString on these objects, since adding them doesn't really make sense.

To display both the item count and chip I suggest you try using React Fragments.

{count: item.count ? <>{item.count}<Chip/></> : '❂'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.