Skip to content

not-only-code/react-i18n

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React i18n

The simplest tool to translate texts in React

installation

npm i @not-only-code/react-i18n

Usage

Create a definitions JSON file per translation.

// translations/en-GB.json
{
  "appHeading": "My App Heading"
}

Add Reacti18nProvider at start up your app. Inject there the locale and messages (a key, value JSON with a locale translations).

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import messages from './translations/en-GB.json';
import { Reacti18nProvider } from '@not-only-code/react-i18n';

ReactDOM.render(
  <Reacti18nProvider locale='en-GB' messages={messages}>
    <App />
  </Reacti18nProvider>,
  document.getElementById('root')
);

Use Reacti18nContext to get t method and translate your definitions:

Using useContext hook

// App.js
import React, { useContext } from 'react';
import { Reacti18nContext } from '@not-only-code/react-i18n';

function App() {
  const { t } = useContext(Reacti18nContext);
  return (
    <div>
      <h1>{ t('appHeading') }</h1>
    </div>
  );
}

export default App;

Using Context.Consumer API syntax

// App.js
import React from 'react';
import { Reacti18nContext } from '@not-only-code/react-i18n';

function App() {
  return (
    <div>
      <Reacti18nContext.Consumer>
        {({t}) => <h1>{ t('appHeading') }</h1>}
      <Reacti18nContext.Consumer>
    </div>
  );
}

export default App;

About

The simplest tool to translate texts in React

Resources

License

Stars

Watchers

Forks

Packages