Tony Hoan Trinh
Tony Hoan Trinh

Reputation: 485

How to have newlines/line breaks within a const string?

I have a string declared as a const in React JS. And I am trying to display it but the appropriate newlines/line breaks aren't not working properly. I tried putting \n within the string itself but it doesn't work and I'm hoping to get some help.

The String Variable itself

const CODE_EXAMPLE = `
const CHECKBOX = {
LABEL: {
    content: SECONDARY_GLOBAL_TEXT,
    disabled: {
      content: SECONDARY_GLOBAL_DISABLED_TEXT
    }
  },
  ERROR_MESSAGE: {
    content: SECONDARY_GLOBAL_ERROR_TEXT
  },
  checked: {
    icon: PRIMARY_GLOBAL_BASE,
    background: TRANSPARENT,
    hover: {
      icon: PRIMARY_GLOBAL_BASE,
      background: SECONDARY_GLOBAL_HOVER,
    },
    disabled: {
      icon: SECONDARY_GLOBAL_DISABLED_CONTENT
    }
  },
}
`;

How I am rendering it

<div className="gray-background">
  {CODE_EXAMPLE} 
</div>

This is what it currently looks like:

enter image description here

This is what it's supposed to look like:

enter image description here

Upvotes: 1

Views: 1003

Answers (4)

Brandon Blessing
Brandon Blessing

Reputation: 1

Part of your problem may be inside your element, where you’re using “classname”, which is just a property mostly used inside JavaScript code (ex. getElementByClassName), whereas inside HTML code, you would only use Some text inside this element… inside an element (using your code as example).

Refer to this for more info: What is the difference between class and classname in javascript?

Upvotes: 0

Evgeny Zaytsev
Evgeny Zaytsev

Reputation: 198

This is an HTML feature, it collapses any extra spaces/new lines by default. You can use tag pre to see the text as is.

Upvotes: 2

iamaword
iamaword

Reputation: 1509

You may be able to accomplish this through css via white-space: pre

This post goes over some options.

Upvotes: 1

Manimegalai V
Manimegalai V

Reputation: 11

\n will not work in JSX. In this case, I would suggest splitting the lines used with special characters.

Upvotes: 0

Related Questions