how to make a new line in react intl?

Viewed 5842

I have a question - how to make a new line in react intl? I put my translations in file like:

[LOCALES.ENGLISH]: {
        'hello': 'Hello',
        }

and call them using . How to make a 2+ lines message??

4 Answers

Use an argument to add a <br/> tag:

const messages = {
  MESSAGE: {
    id: "message",
    defaultMessage: "<p>Message with {br} linebreaks</p>"
  }
};

export default function App() {
  return (
    <IntlProvider locale="en" messages={messages}>
      <div className="App">
        <FormattedMessage
          {...messages.MESSAGE}
          values={{
            p: (...chunks) => <p>{chunks}</p>,
            br: <br />
          }}
        />
      </div>
    </IntlProvider>
  );
}

Full sandbox: https://codesandbox.io/s/formattedmessage-key-error-6kx6c?file=/src/App.js

you can use message with variable and send <br/> as value of variable like fallowing :

    <FormattedMessage {...strings.headTitle} values={{br: <br/>}} />

strings :

export default defineMessages({
  headTitle: {
    id: 'test',
    defaultMessage: 'test {br} next line',
  } })

In case anyone is still looking for a fix.

you could use \n and use white-space: pre-line styles.

{'hello': 'Hello \n World'}

<p style="white-space: pre-line;"><FormattedMessage id="hello"/></p>

Import ReactHtmlparser from 'react-html-parser';

In class construtor below super () add This.formatMessage = props.intl.formatMessage

And use in your jsx

{ReactHtmlparser (this.formatMessage ({id : "your id"}) )}

export default injectIntl(MyClass);

Related