React-Intl: access formatMessage in nested component

The question is simple and Im can’t believe I cant found a solution (without context) for a situation as simple as this.

Im using react-intl.
I have an App.jsx with a child component Index.jsx with a SideBar.jsx with a CreateNewSomething.jsx.

In every components, the command

     defaultMessage='Please fill the "title" parameter'

works perfectly thanks to <IntlProvider> provided by App.jsx

Unfortunally, I can’t inject FormattedMessage as state value of a component.


 error= { this.state.title_error }

When the input field is not filled (is required) I want to print an error message.
Unfortunally I can’t write:

const error_message = <FormattedMessage
            defaultMessage='Please fill the "title" parameter'

this.setState({"title_error" : error_message});

because I get [object Object] and there is no property inside of it with my translated message.

Searching everywhere, I found I have to use this.props.intl.formatMessage({id: 'new_dash.fill_title'});

but this.props.intl is undefined.

I’ve tried, in App.jax, to include:

import {addLocaleData, IntlProvider, injectIntl, intlShape} from 'react-intl';

but it makes no difference.

I’ve tried to pass intl to every child component as props but intl is undefined in App.jsx too.

I don’t know where is my mistake.

One thought on “React-Intl: access formatMessage in nested component”

  1. The module’s Wiki explain the method but not how to use.
    The solution is simple. You have to change the Export Syntax of your React Component and than this.props.intl will be magically available in the component:
    export default injectIntl(MyComponent); //WORKS!!!
    export default class injectIntl(MyComponent) extends React.Component //DOESN'T WORK

Leave a Reply

Your email address will not be published.