reactjsreact-intl

how to define defaultprops using hook useIntl


Recently I started using the hook useIntl, previously I was using the HOC injectIntl. Now I am facing a problem I can't find a solution, how to internationalize the defaultProps?

Something like:

function Component(props) {
    const intl = useIntl();
    const {name} = props;

    return (
      <div>
         {intl.formatMessage({id: 'welcome'}, {user: name})}
      <div/>
    );
}

Component.defaultProps = {
   name: 'unknown'; <<---------- how to replace this plain string with intl...?
}

Component.propTypes = {
   name: PropType.string
}

export default Component;

Solution

  • You can use FormattedMessage:

    import { FormattedMessage, useIntl } from 'react-intl';
    
    function Component(props) {
        const intl = useIntl();
        const {name} = props;
    
        return (
          <div>
             {intl.formatMessage({id: 'welcome'}, {user: name})}
          <div/>
        );
    }
    
    Component.defaultProps = {
       name: <FormattedMessage id="unknownKey" />
    }
    
    Component.propTypes = {
       name: PropType.string
    }
    
    export default Component;