react-text

Text and translation handling with React made simple

React Text npm install react-text gzip size

React text translation with dictionaries. An easy to use and flexible library to fulfill your translation needs:

import Text from 'react-text';
import dictionary from './dictionary';

export default () => (
  <Text language="ja" dictionary={dictionary}>
    <p><Text greetings /></p>
    <p><Text farewell name="Francisco" /></p>
  </Text>
);
// <p>こんにちは、世界!</p>
// <p>さよなら、FRANCISCOさん!</p>

Contents:

  • Getting started: Introduction to how to start using react-text with React.
  • Dictionary: define the translations and some basic transformations.
  • Configuration: set the language and inject the dictionary.
  • Translate: use &lt;Text&gt; with a id to create translations with optional properties.
  • Render: inject a translated string into a React component. Useful for alt={} and similar.
  • Component: renders only for the right language.

Getting started

First let’s install the package with npm:

npm install react-text

Then we define a dictionary of the text to translate:

// ./dictionary.js
export default {
  greetings: {
    en: 'Hello world!',
    es: '¡Hola mundo!',
    ja: 'こんにちは、世界!'
  }
};

To use those, we need to create a wrapping <Text> with two options: the dictionary and the language. Then inside it, we create a self-closing <Text /> tag with the property as the previously defined key of the object:

// ./Example.js
import Text from 'react-text';
import dictionary from './dictionary';

export default () => (
  <Text language="es" dictionary={dictionary}>
    <p><Text greetings /></p>
  </Text>
);
// ~> ¡Hola mundo!

Dictionary

The dictionary is defined as an object of objects. The first level (greetings) is what we call the id, the second is the language (en) and finally we have the values (Hello world and functions):

// ./dictionary.js
export default {
  greetings: {
    en: 'Hello world!',
    es: '¡Hola mundo!',
    ja: 'こんにちは、世界!'
  },
  farewell: {
    en: ({ name = 'World' }) => `Hello ${name}!`,
    es: ({ name = 'Mundo'}) => `¡Adiós ${name}!`,
    ja: ({ name = '世界' }) => `さよなら、${name.toUpperCase()}さん!`
  }
};

All the languages must be the same in all the entries, otherwise it will throw an error. The order is important as well, since the first language will be considered the default one if it cannot be found otherwise.

Subscribe to the Newsletter

Get our latest news,tutorials,guides,tips & deals delivered to your inbox.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

shares