Home > Blockchain >  Conditional line break
Conditional line break

Time:11-26

I only want to line break if variable var is not a null value, how would I go about this?

<div>
{var && `${var}`} <br />
{var2 && `${var2}`}
</div>

CodePudding user response:

If you are only checking for null

{var !== null ? '<br />' : ''}

If any falsy statement is the condition you want to check (undefined , null , NaN , 0 , "" , and false)

{var ? '<br />' : ''}

CodePudding user response:

Like any other conditional element

<div>
  {var && `${var}`}
  {var && <br />}
  {var2 && `${var2}`}
</div>

Or shorter,

<div>
  {var && <>{`${var}`}<br /></>}
  {var2 && `${var2}`}
</div>

CodePudding user response:

Try using

{var ? '<br />': ''}

CodePudding user response:

You are creating HTML in JavaScript, so I assume you have used back-ticks around opening and closing div first. Then based on the value of var, You want to set the break point.

First thing is var is a keyword in Javascript and should not be used as the variable name.

Second is we can do something like this using ES6 back-ticks and interpolation.

    let myVaribale = 23; // Not Null
    const htmlTest = `<div>
          <span>Testing the line-break</span>
          ${myVaribale && `<br/>` }
          <p> Life is a test</p>
    </div>`;

document.body.innerHTML = htmlTest;
<html>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related