react-intl.macro
react-intl.macro copied to clipboard
Using defineMessages with FormattedMessage
trafficstars
We're currently moving to react-intl.macro from react-intl-cra and running into an issue with our FormattedMessage components.
Previously, we imported defineMessages and FormattedMessage from 'react-intl'. Doing this, we were able to use the spread operator in our FormattedMessage to pass in the correct message attributes.
Now, we import defineMessages and FormattedMessage from 'react-intl.macro' and when trying to extract messages get the following error:
TypeError: react-intl.macro: Cannot read property 'name' of undefined
Example Code:
import React from 'react';
import './App.css';
import {defineMessages, FormattedMessage} from 'react-intl.macro';
function App() {
const messages = defineMessages({
name_hello_user_text: {
id: 'name.hello.user',
defaultMessage: 'Hello! Welcome!'
}
});
return (
<>
{/*this works*/}
<h1><FormattedMessage id="app.title" defaultMessage="Sample App" /></h1>
{/*this no longer works*/}
<FormattedMessage
{...messages.name_hello_user_text}
/>
</>
);
}
export default App;
Workaround:
import { defineMessages } from 'react-intl.macro';
import { FormattedMessage } from 'react-intl';