reactjsreact-intl

React-intl for non components


Currently I have the following code to expose react-intl to non-components, but it throws an error for intl as undefined.

I have created a separate component as 'CurrentLocale' and inject-intl to it. The exporting function t will use intl formatMessage from CurrentLocale context.

import React from 'react';
import {injectIntl} from 'react-intl';
import PropTypes from 'prop-types';
import { flow } from 'lodash';

class CurrentLocale extends React.Component {


    constructor(props,context){

        super();
        console.log(context,props);
        console.log(this.formatMessage);
        const { intl } = this.context.intl;//this.props;

        this.formatMessage = intl.formatMessage;
    }

    render() {
        return false;
    }
}
CurrentLocale.contextTypes={
    intl:PropTypes.object,
};


injectIntl(CurrentLocale);

function intl() {
    return new CurrentLocale();
}

function formatMessage(...args) {
    return intl().formatMessage(...args);
}


const t = opts => {
    const id = opts.id;
    const type = opts.type;
    const values = opts.values;
    let t;

    switch (type){

        case 'message':
        default:
            t = formatMessage(id, values);
    }

    return t;
}

export default t;

t is called as in another plain javascript file as,

import t from './locale/t';
t( { type: 'message', id:'button.Next'});

Following is the error message. enter image description here Thanks in advance.


Solution

  • This line: const { intl } = this.context.intl; should be const { intl } = this.context;

    Here is a reference post of someone doing almost the exact same thing as you are: https://github.com/yahoo/react-intl/issues/983#issuecomment-342314143

    In the above the author is creating essentially a singleton that is exported instead of creating a new instance each time like you have above. This might be something you want to consider as well.