Hervera
Hervera

Reputation: 592

React - If condition outside an html tag attribute

I know that a condition inside an attribute works fine, but this gives a string of false in the data-tip attribute when active is false.

<div data-tip={active && 'hello'}>

...
</div>

I want the data-tip attribute to not be shown in the rendered component when active is false <div> ... </div>. If think I can do that if I add a condition outside the data-tip attribute, but it is failing.

<div {active && data-tip='hello'}>

...
</div>

How can I achieve this without putting the condition outside the div element?

Upvotes: 0

Views: 911

Answers (2)

Shankar Ganesh Jayaraman
Shankar Ganesh Jayaraman

Reputation: 1501

Try with the spread operator,

    let dataTipProps = {
       id:'foo'
    };

    let active = true;

    if(active)
       dataTipProps['data-tip'] ='hello';

Render with spread, optionally passing other props also.

    <div {...dataTipProps}>
    
    ...
    </div>

It will be appearing in HTML as

    <div id='foo' data-tip='hello'> //if active
    <div id='foo'> //if !active

Upvotes: 2

ThatAnnoyingDude
ThatAnnoyingDude

Reputation: 562

If you pass undefined it will not be rendered.

<div data-tip={!active ? undefined : 'hello'}>

</div>

Upvotes: 3

Related Questions