简体   繁体   中英

how to make a new line in react intl?

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??

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM