Home > Software engineering >  React ternary operator return jsx and string returns an Object
React ternary operator return jsx and string returns an Object

Time:06-02

I need to check if the form has been submitted, if it was successfull then display one thing if not another. The code I have is

                   {success !== undefined ? 
                        success ? <CheckOutlined />   ' Subscribed' : (<CloseOutlined />   ' Error!' )
                    : 'Subscribe'}

Undefined is the first state when the form is first loaded. What I get returned after the form is submitted successfully is

[object Object] Subscribed

If I don't add the string everything is fine and I can see the jsx. How can I get them both to view using ternary?

CodePudding user response:

Just try success ? (<CheckOutlined /> Subscribed) : (<CloseOutlined /> Error!)

CodePudding user response:

You are concatenating JSX element in string that's why it is giving [Object Object] Subscribed. Correct way is:

{success !== undefined ? 
                        success ? (<CheckOutlined /> ' Subscribed') : (<CloseOutlined /> ' Error!' )
                    : 'Subscribe'}
  • Related