0

the variable twitter_username resolves to either a username or null.

 {{twitter_username}?<p>@{twitter_username}</p>:null}

I want this to display @username if there is a username or nothing at all if the value is null. If there is a username it displays fine but if the return is null I get an @ instead of nothing.

 {{twitter_username}?<p>{twitter_username}</p>:null}

this code returns the username if there is a username and is blank when there is none.

Cat Boxer
  • 47
  • 7
  • 1
    Does this answer your question? [if-else statement inside jsx: ReactJS](https://stackoverflow.com/questions/44046037/if-else-statement-inside-jsx-reactjs) – Emile Bergeron Nov 11 '20 at 23:23
  • `{twitter_username}` creates an object `{ twitter_username: twitter_username }` which is always truthy in JS. – Emile Bergeron Nov 11 '20 at 23:24

1 Answers1

2

a nice and easy way to do it { twitter_username && (<p>@{twitter_username}</p>) }

Here the left part of the ternary operator will continue to the right only if the first part (twitter_username) if defined. The right part is a return statement who returns jsx

Maxime Oger
  • 160
  • 1
  • 8