Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I formatMessage with a tags (links) using react-intl?

I need to add links to the text I need translated. How can I formatMessages that have links?

Right now this is what I am trying to do:

const messages = defineMessages({
  copy: {
    id: 'checkout.OrderReview.copy',
    description: 'Label for add card button',
    defaultMessage: 'By clicking the "Place Order" button, you confirm that you have read, understood, and accept our {termsAndConditionsLink}, {returnPolicyLink}, and {privacyPolicyLink}.',
  },
  termsAndConditions: {
    id: 'checkout.OrderReview.termsAndConditions',
    description: 'Label for terms and conditions link',
    defaultMessage: 'Terms and Conditions',
  },
  returnPolicy: {
    id: 'checkout.OrderReview.returnPolicy',
    description: 'Label for return policy link',
    defaultMessage: 'Return Policy',
  },
  privacyPolicy: {
    id: 'checkout.OrderReview.privacyPolicy',
    description: 'Label for privacy policy link',
    defaultMessage: 'Privacy Policy',
  },
});

Then, in the render function:

  const copy = formatMessage(messages.copy, {
    termsAndConditionsLink: <a href="#" className="u-underline text-color-grey">`${formatMessage(messages.termsAndConditions)}`</a>,
    returnPolicyLink: <a href="#" className="u-underline text-color-grey">`${formatMessage(messages.returnPolicy)}`</a>,
    privacyPolicyLink: <a href="#" className="u-underline text-color-grey">`${formatMessage(messages.privacyPolicy)}`</a>,
  });

return <div> { copy } </div>

This doesn't work. I get: By clicking the "Place Order" button, you confirm that you have read, understood, and accept our [object Object], [object Object], and [object Object].

What is the correct way to accomplish this task?

like image 478
Stephani Bishop Avatar asked Dec 13 '16 20:12

Stephani Bishop


1 Answers

First, it depends on your react-intl version. I've made it work using react-intl v2.x (2.8 to be exact). Here's how I did:

const messages = defineMessages({
  copy: {
    id: 'copy',
    defaultMessage: 'Accept our {TermsAndConditionsLink}',
  },
  termsAndConditions: {
    id: 'termsAndConditions',
    defaultMessage: 'Terms and conditions',
  },
  termsAndConditionsUrl: {
    id: 'termsAndConditionsUrl',
    defaultMessage: '/url',
  },
});

<FormattedMessage
  {...messages.copy}
  values={{
    TermsAndConditionsLink: (
      <a href={intl.formatMessage(messages.termsAndConditionsUrl)}>
        {intl.formatMessage(messages.termsAndConditions)}
      </a>
    ),
  }}
/>

For newer react-intl version, you can find your answer in the docs:

v3.x: https://formatjs.io/docs/react-intl/upgrade-guide-3x#enhanced-formattedmessage--formatmessage-rich-text-formatting

v4.x: https://formatjs.io/docs/react-intl/api/#formatmessage

like image 152
Renaud Avatar answered Nov 10 '22 16:11

Renaud