0

simple question here having this :

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

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

Client : client libelle

4
  • 1
    Just do {!!elt.client && "Client : client libelle"}. If the string is dynamic, you can do { !!elt.client && "Client : " + elt.client.libelle}. Adding double ! will parse your first statement to a boolean which is basically an exists check. If you add && and the first argument is true, the part after will be returned and displayed. If the value is false, nothing will be displayed. Commented May 31, 2022 at 12:44
  • I'm still getting client : null with {!!elt.client && "Client : client libelle"} when client isn't defined. But you understood what i want Commented May 31, 2022 at 13:11
  • Ok never mind im dumb, with !!elt.client.libelle, it works. Thanks a lot man Commented May 31, 2022 at 13:14
  • 1
    No worries, you're welcome. Commented May 31, 2022 at 13:19

2 Answers 2

1

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" }

`

Sign up to request clarification or add additional context in comments.

4 Comments

Or { elt.client && elt.client.libelle } or { el.client?.libelle || 'something else' }
I want to display either nothing if client isn't defined or "client : client libelle" if client is defined
You can still use the if statement then, can you not?
I can't because it is in an html return (with react hooks)
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.