@opuscapita/react-i18n

2.0.1 • Public • Published

CircleCI Status Coverage Status npm version Dependency Status NPM Downloads badge-license

OpusCapita React i18n

i18n module extension for React applications that provides several components (tags) for rendering i18n messages.

Assumptions

Everything is stored in i18n (I18nManager instance) object in scope of React context.

Usage

App

React application should initialize i18n object and propagate it for child components.

/**
 * App
 */
class App extends React.Component {
  static propTypes = {
    locale: React.PropTypes.string.isRequired
  };

  static childContextTypes = {
    i18n: React.PropTypes.object.isRequired
  };

  getChildContext() {
    return {
        i18n: new I18nManager(this.props.locale)
    };
  }

  render() {
    return (

      <div>
        <MyComponent />
      </div>

      );
  }
}

export default function(element, props) {
  return React.render(<App {...props} locale="en-US" />, element);
};

Component

Each component may register own messages in global i18n using register method of I18nManager.

/**
 * Root element of custom component.
 */
class MyComponent extends React.Component {
  static contextTypes = {
    i18n: React.PropTypes.object.isRequired
  };

  static childContextTypes = {
    i18n: React.PropTypes.object.isRequired
  };

  getChildContext() {
    const translations = [{
      locales : ['en-US'],
      messages: {
          logo: {
              title: 'Title',
              text: 'Text'
          }
      }
    }];

    return {
        i18n: this.context.i18n.register('MyComponent', translations)
    };
  }

  render() {
    return (
      <header className="header-style">
        <a href="#" className="logo-style" title={this.context.i18n.getMessage('logo.title')}>
          <FormattedMessage message="logo.text" />
        </a>
      </header>
    );
  }
}

Development

Run code linting

npm run lint

Run tests

npm test

Start demo

npm start

/@opuscapita/react-i18n/

    Package Sidebar

    Install

    npm i @opuscapita/react-i18n

    Weekly Downloads

    18

    Version

    2.0.1

    License

    Apache-2.0

    Unpacked Size

    58.9 kB

    Total Files

    20

    Last publish

    Collaborators

    • ariusz
    • ilhamkadduri
    • smachnow
    • piotr.krzysztof.murdzia
    • kuos
    • elaczapiewska
    • janek.bug
    • ocmachineuser
    • ocautomation