Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve a string in ReactIntl 2.0 without using FormattedMessage

Please correct me if I am wrong, FormattedMessage in ReactIntl returns a string wrapped by span tags. In ReactIntl 1.2, we have the option to use this.getIntlMessage('key') to get only the string part.

Here is my question: Is there an equivalent of that in ReactIntl 2.0? I am aware that the string can be obtained by using the Function-As-Child pattern in FormattedMessage as

<FormattedMessage id="placeholder">
    {(formattedValue)=>(
        <MyComponent ref="mycomponent" placeholder={formattedValue}/>
    )}
</FormattedMessage>

However, it messes up the 'ref' in my component and I can't access to the component using this.refs.mycomponent any more.

like image 587
C.Lee Avatar asked Feb 03 '16 19:02

C.Lee


3 Answers

There is a better to solve placeholder problem.

<FormattedMessage ...messages.placeholderIntlText>
  {
     (msg) =>  <input type="text" placeholder = {msg} />
  }
</FormattedMessage>
like image 95
Jacky Hu Avatar answered Nov 08 '22 20:11

Jacky Hu


You can easily return string using intl object provided by react-intl.

this is how you use intl object inside react class in much more easier way.

note: Render Component (main component) should wrap with IntlProvider

class MySubComponent extends React.Component{
  {/*....*/}

  render(){
    return(
     <div>
        <input type="text" placeholder = {this.context.intl.formatMessage({id:"your_id", defaultMessage: "your default message"})}
     </div>

    )
  }
   }
MySubComponent.contextTypes ={
 intl:React.PropTypes.object.isRequired
}

By defining contextTypes it will enable you to use intl object which is a context type prop. See react context for more details.

like image 9
Kinsly Roberts Avatar answered Nov 08 '22 22:11

Kinsly Roberts


Ok, there is a work around for that. I can add ReactIntl as the context in the component like this:

contextTypes: {
    intl: React.PropTypes.object.isRequired,
},

Then when trying to retrieve the string of the message and use it, for example in a placeholder, I can do this.

<MyComponent ref="mycomponent" placeholder={this.context.intl.messages.placeholder}/>
like image 5
C.Lee Avatar answered Nov 08 '22 22:11

C.Lee