stackuser
stackuser

Reputation: 283

How to render a string using nested ternary operator using react?

i want to display a particular string based on condition using ternary operator using react.

below is my code,

const ChildComponent = (data) => {
    const name = data.name //array
    const type = data.type //object

    return (
        <div>{type.name} {type.id} </div> //here condition to be added
    );
}

for the above code in return block type.name and type.id are displayed.

now i want to display name if there is type and type.name. id should be shown if type and type.id and "none" to be displayed if no type and type.name or type.id

could someone help me get this fixed. thanks.

Upvotes: 0

Views: 96

Answers (1)

Benni
Benni

Reputation: 654

You could do something like this

const ChildComponent = (data) => {
    const name = data.name //array
    const type = data.type //object

    return (
        <div>{type && type.name ? name : type && type.id ? type.id : "none"}</div>
    );
}

I am not sure if I understood all the conditions that you wanted to have, but I hope you get the concept.

Upvotes: 1

Related Questions