Search code examples
javascriptreactjsecmascript-6material-uiconditional-operator

Ternary Operator in ReactJs Card Header


How can i put a ternary operator in the title of CardHeader in ReactJS? I can only put one the first Name but not the last name.

<CardHeader title={(firstName ? firstName : "")(lastName ? lastName : "")} />;

Solution

  • You can use multiple ternary operator in the same string:

    <CardHeader title={`${(firstName ? firstName : "")} ${(lastName ? lastName : "")}`} />
    

    In your case i would use a function to generate the full name:

    const getFullName = () => {
        const name = []
        if(firstName) name.push(firstName)
        if(lastName) name.push(lastName)
        return name.join(' ')
    }
    // ...
    <CardHeader title={getFullName()} />