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?

3
  • 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? Commented May 29, 2023 at 4:57
  • Try changing the newline character to a <br> tag. Commented May 29, 2023 at 4:58
  • 2
    white-space: pre might be a better style to apply. It will break lines at \n characters. Commented May 29, 2023 at 5:06

1 Answer 1

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);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.