RedWitch
RedWitch

Reputation: 153

Add a default message to display if no other messages available

I have a text editor and a div that shows error messages on the side if errors are detected in typed text. I am trying to set a default message that should be displayed when no errors are detected.

Here is my div:

<WarningContainer>
{warnings.length > 0 && warnings.map(warning => <Warning>{warning.text}</Warning>)}
</WarningContainer>

I have tried adding another line with a condition to display some text if the length of warnings.lenhtg == 0 but it broke the second part that dynamically displays a warning:

<WarningContainer>
{warnings.length == 0 && warnings.map(warning => <Warning>`Some default text.`</Warning>)}
{warnings.length > 0 && warnings.map(warning => <Warning>{warning.text}</Warning>)}
</WarningContainer>

How can I add a default message to be only displayed when no warnings are available? Thank you

Upvotes: 0

Views: 113

Answers (1)

norbitrial
norbitrial

Reputation: 15166

You can use ternary operator for this purpose. Render the <Warning /> components once you have values in the warnings array or render a simple <span> with default message as:

<WarningContainer>
  {warnings.length > 0 ?
      warnings.map(warning => <Warning>{warning.text}</Warning>) :
      <span>Some default warning</span>
  }
</WarningContainer>

Read further about Conditional (ternary) operator:

The conditional (ternary) operator is the only JavaScript operator that 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. This operator is frequently used as a shortcut for the if statement.

Upvotes: 1

Related Questions