OpusCapita / react-i18n

OpusCapita React i18n Extension

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

About

OpusCapita React i18n Extension

License:Apache License 2.0


Languages

Language:JavaScript 97.2%Language:HTML 2.8%