Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass a parameter to defineMessages in react-intl?

I have an error message like the one below:

Could not retrieve data: ${e}

How do I convert this to a definedMessage that can accept this error parameter?

A standard definedMessage:

    const messages = defineMessages({
     dataError: {
         id: 'data.error',
         defaultMessage: 'Could not retrieve data: [default message]'
     }
   })

Thanks!

like image 377
reectrix Avatar asked May 11 '18 18:05

reectrix


People also ask

What is injectIntl?

injectIntl HOC​ This function is exported by the react-intl package and is a High-Order Component (HOC) factory. It will wrap the passed-in React component with another React component which provides the imperative formatting API into the wrapped component via its props .


2 Answers

If I understood you correctly like this:

const messages = defineMessages({
  dataError: {
    id: 'data.error',
    defaultMessage: 'Could not retrieve data: {message}'
  }
})

<FormattedMessage
  {...messages.dataError}
  values={{message: `Could not retrieve data: ${e}`}}
/>
like image 80
Tomasz Mularczyk Avatar answered Sep 18 '22 06:09

Tomasz Mularczyk


need to replace [default message] with {e} in defineMessages

const messages = defineMessages({
  dataError: {
    id: 'data.error',
    defaultMessage: 'Could not retrieve data: {e}'
  }
})

Define Message variable

 const message = "Error Message";

Pass message variable in Formatted Message

 <FormattedMessage
          {...messages.dataError}
          values={{ e: `${message}` }}
 />

Out Put in below

<span>Could not retrieve data: Error Message</span>

Hope it will help you.

like image 25
USS Avatar answered Sep 21 '22 06:09

USS