Kiji_T
Kiji_T

Reputation: 104

How to print html text depending on condition using reactJs?

simple question here having this :

<Row>
   { "Client : " && elt.client?.libelle}
</Row>

I'd like that if elt.client is defined, displaying :

Client : client libelle

Upvotes: 0

Views: 555

Answers (2)

subodhkalika
subodhkalika

Reputation: 2247

You can make use of ternary operator (? and : ). This operator is frequently used as an alternative to an if...else statement.

<Row>
 { elt?.client?.libelle ? ("Client : " + elt.client.libelle) : "" }
</Row>

It takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.

Also, you can utilise optional chaining (?.) operator of JavaScript which prevents an error if a reference is nullish (null or undefined).

In this case, if elt is undefined, it won't throw error. Hence, if all elt, elt.client and elt.client.libelle is defined and the value is no null, "Client : " + elt.client.libelle will display.

Upvotes: 1

eskil4152
eskil4152

Reputation: 147

Not sure exactly what you mean, but maybe this help?

<Row>
  {elt.client ? elt.client.libelle : elseStatement}
</Row>

Meaning: `if (elt.client) { return elt.client.libelle } else { return "whatever else you want" }

`

Upvotes: 1

Related Questions