Ajinkya
Ajinkya

Reputation: 1711

Conditional rendering with ternary operator in react

I am trying to conditionally render few messages on my page. Following is the simplified code of my actual scenario.

<div>
    {
        isCondition1 == true ?
           'Show issue list'
        :
            isConditionA == true?
               'Show message for condition A'
            :
                'Show error message'
    }
</div>
<div>
    {
        isCondition2 == true?
           'Show team issue list'
        :
            isConditionA == true?
               'Show message for condition A'
            :
               'Show error message'
    }
</div>

I want to take out common things from the above and use it in the code.

const msgNoIssues = (
    isConditionA == true?
       'Show message for condition A'
    :
       'Show error message'
);

And use it as follows:

<div>
    {
        isCondition1 == true?
           'Show issue list'
        :
           {msgNoIssues}
    }
</div>
<div>
    {
        isCondition2 == true ?
           'Show team issue list'
        :
           {msgNoIssues}
    }
</div>

But it is giving an error message:

Objects are not valid as a React child (found: object with keys {msgNoIssues}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.

Can it be achieved without react add-ons? Is there any better way of doing it?

Upvotes: 2

Views: 4927

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104379

When {} is needed in JSX?

We need to use {} to put js expressions inside JSX, so put ternary operator inside {}.

Reason of this error: Objects are not valid as a React child

Meaning of { msgNoIssues } is { msgNoIssues: msgNoIssues } that means you are trying to render an object with key msgNoIssues, that's why it is throwing the error: Objects are not valid as a React child (found: object with keys {msgNoIssues}).

Solution:

Remove {} around the msgNoIssues, write it like this:

<div>
    {
        isCondition1 == true ?
            'Show issue list'
        :
            msgNoIssues
    }
</div>
<div>
    {
        isCondition2 == true ?
            'Show team issue list'
        :
            msgNoIssues
    }
</div>

Check this Snippet (meaning of { a }):

let a = 10;

let obj = {a};

console.log('obj = ', obj);

Check the DOC: Embedding Expressions in JSX and Conditional Rendering

Upvotes: 1

Related Questions