When you're working with localization messages in React, it's important to remember that by default, web browsers don't recognize the \n
character as a line break. This can cause problems with the formatting of your messages.
One way to solve this problem is to set the white-space
CSS property to pre-line
, which tells the browser to treat \n
as a line break. However, this approach may cause unexpected issues in some situations, so it's not always the best choice.
A better approach is to use the <br/>
element in your localization message to indicate where line breaks should occur. Then, when you render the message, you can pass the message as a string with the <br/>
elements included. This way, the browser will interpret the <br/>
tags as line breaks and display your message correctly.
The example below uses the react-intl localization library, but other localization libraries likely have similar options for including HTML in messages.
The localization message:
"common.welcome": "Welcome!{br}Glad to see you again!"
The usage in the code:
const intl = useIntl();
const message = intl.formatMessage({ id: "common.welcome" }, { br: <br/> });