TheUnreal
TheUnreal

Reputation: 24472

React - conditional parent component

I have the following component composition:

<Badge.Ribbon text={ribbonText}>
      <Card className={'userCard'}
            hoverable
      >
        Some Data
      </Card>
</Badge.Ribbon>

I want to show the Badge.Ribbon component only in case ribbonText is not null. It means that when ribbonText is null, I don't want to use the Badge.Ribbon parent component (which warps the whole component).

What is the ideal way in React to deal with it?

The only solution that comes into my mind is to create a new component for each card, e.g someCard and ribonnedCard for cards with a ribbon, but I wonder if there is another solution without creating a new component for each use case.

Thanks!

Upvotes: 1

Views: 1549

Answers (3)

Ian Mutawa
Ian Mutawa

Reputation: 503

Creating a wrapper would do the trick:

const wrapper = (condition, child) => condition ? <Wrapper>{child}</Wrapper> : child;

Upvotes: 1

im_tsm
im_tsm

Reputation: 2051

This will render the wrapped Card inside Badge.Ribbon when ribbonText is not null.

{ribbonText !== null ? (
  <Badge.Ribbon text={ribbonText}>
    <Card className={'userCard'} hoverable>
      Some Data
    </Card>
  </Badge.Ribbon>
) : (
  <Card className={'userCard'} hoverable>
    Some Data
  </Card>
)}

Also, depending upon your requirement you can simply check truthy value of ribbonText by {ribbonText ? <Component1/> : <Component2 />}.

For className you can directly provide string like this <Card className="userCard" hoverable>

Upvotes: 0

TheZver
TheZver

Reputation: 1582

let result = (
    <Card
        className='userCard'
        hoverable
    >
        Some Data
    </Card>
);

if (ribbonText !== null) {
    result = (
        <Badge.Ribbon text={ribbonText}>
            {result}
        </Badge.Ribbon>
    );
}

Upvotes: 4

Related Questions