dragonfly
dragonfly

Reputation: 3227

How to add RectIntl Formatted message as html attribute

I have a header logo image for which alt and title attribute should render from i18n messages.

message_en.json

{
    "logoTitle": "Link open in new tab or window",
    "logoAlt": "some description goes here.." 
}

header.js

import { FormattedMessage } from 'react-intl/dist';

<a
  href={url}
  title={<FormattedMessage id="logoTitle"/>}
> 
  <img
      src={src}
      alt={<FormattedMessage id='logoAlt' />}
  />
</a>

In the browser, alt and title renders as [Object][Object]

<a title="[object Object]">
    <img id="masthead__logo__img" src="../assets/images/logo.png" alt="[object Object]">
</a>  

How do I render FormattedMessage in this case?

Upvotes: 1

Views: 3595

Answers (2)

Ross Sheppard
Ross Sheppard

Reputation: 870

Potential Solution

Use the useIntl hook to render a plain string.

import { useIntl } from 'react-intl'; 

const intl = useIntl(); // place this within your function / class.
<a
  href={url}
  title={intl.formatMessage({ id: 'logoTitle' })} />}
> 
  <img
      src={src}
      alt={intl.formatMessage({ id: 'logoAlt' })} />}
  />
</a>

Debugging

You can console.log(intl.formatMessage({ id: 'logoTitle' }); outside of the prop to see what value is being fetched for that identifier.

Upvotes: 0

kind user
kind user

Reputation: 41893

FormattedMessage is a React component that renders HTML. To render a plain string, use intl.formatMessage function instead:

title={intl.formatMessage({ id: 'logoTitle' })}

Upvotes: 1

Related Questions