2

I want to create multiline text using multiple ternary operators within a single Template literal.

const toolTipText = `${2 * 5 === 10 ? "The value is same" : ""}
  ${"a" === "b" ? "" : "Different letters"}`;

console.log(toolTipText);

For example, in the code above, I want The value is same in one line & Different letters in the next line. However, they are both in the same line. I am basically trying to add lines on text based on conditions.

How to achieve it?

Rohad Bokhar
  • 104
  • 9
moys
  • 7,747
  • 2
  • 11
  • 42
  • The site does not allow me to accept the answer within 10mins, hence I was unable to accept. BTW, just on follow-up. Even though the text is a multiline text in JS, it is being rendered as a single line in my browser (React App), I tried `white-space: nowrap;` in CSS but no luck. Any suggestions? – moys May 29 '23 at 04:57
  • Try changing the newline character to a `
    ` tag.
    – Michael M. May 29 '23 at 04:58
  • 2
    `white-space: pre` might be a better style to apply. It will break lines at `\n` characters. – Carsten Massmann May 29 '23 at 05:06

1 Answers1

0

Try adding \n (the escape sequence for a newline character) after The value is same in the ternary expression. This way, a new line will only show when there are two different lines that need to be shown:

const toolTipText = `${2 * 5 === 10 ? "The value is same\n" : ""}${"a" === "b" ? "" : "Different letters"}`;
console.log(toolTipText);
Michael M.
  • 10,486
  • 9
  • 18
  • 34