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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With