Reputation: 24472
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
Reputation: 503
Creating a wrapper would do the trick:
const wrapper = (condition, child) => condition ? <Wrapper>{child}</Wrapper> : child;
Upvotes: 1
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
Reputation: 1582
let result = (
<Card
className='userCard'
hoverable
>
Some Data
</Card>
);
if (ribbonText !== null) {
result = (
<Badge.Ribbon text={ribbonText}>
{result}
</Badge.Ribbon>
);
}
Upvotes: 4