react-text

by franciscop

franciscop / react-text

📙 React translation library with plain objects as dictionaries

124 Stars 2 Forks Last release: Not found MIT License 35 Commits 9 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

React Text npm install react-text test badge gzip size

React and React Native translation library with plain objects as dictionaries:

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

export default () => (

); //

こんにちは、世界!

//

さよなら、FRANCISCOさん!

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
     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

 with two options: the dictionary and the language. Then inside it, we create a self-closing 
 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 () => (

); // ~> ¡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.

Configuration

Once we have the dictionary, we have to determine how and where to inject it, as well as specifying the language. This will be done by creating a

 element with children:
import Text from 'react-text';
import dictionary from './dictionary';

export default () => ( {/* Here the language will be English */} );

For React Native, any of the usual props of

...
can be passed here.

They can be set at different levels, which is specially useful if you want to split the dictionary into different pages:

import Text from 'react-text';
import dictionaryA from './dictionaryA';
import dictionaryB from './dictionaryB';

export default () => ( {/* English for Dictionary A /}

{/ English for Dictionary B */}
);

When nesting dictionaries they will cascade and the latter ids will override the previous ids.

const dictA = {
  greetings: { en: 'Hello world' },
  farewell: { en: 'Goodbye world' }
};
const dictB = {
  greetings: { en: 'Hey world!' }
};

export default () => (

); //

Hello world

//

Hey world!

//

Goodbye world

The language would normally be a variable that comes from your own code:

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

export default ({ language = 'en' }) => ( {/* Here the language will be English */} );

The language can also be nested, and it will use the most specific (innermost):

const dictionary = { greetings: {
  en: 'Hello world!',
  es: '¡Hola mundo!',
  ja: 'こんにちは、世界!'
}};

export default () => (

); //

Hello world!

//

こんにちは、世界!

//

¡Hola mundo!

While nesting dictionaries is totally fine and expected, nesting languages might get messy and it's recommended to avoid it if possible. Use a global store like Redux to handle the language instead and inject it at the root level:

// LanguagePicker.js
// Example implementation with Redux and an action creator
const setLanguage = payload => ({ type: 'SET_LANGUAGE', payload });
export default connect(({ language }) => ({ language }))(({ language, dispatch }) => {
  
     dispatch(setLanguage('en'))}>English
     dispatch(setLanguage('es'))}>Spanish
     dispatch(setLanguage('ja'))}>Japanese
    

Current language: {language}

});

// reducers/index.js export default combineReducers({ // ... language: (state = 'en', { type, payload }) => { return (type === 'SET_LANGUAGE') ? payload : state; } });

Translate

With the dictionary and language injected, use

 with a self-closing tag and the right id:
const dictionary = {
  greetings: {
    en: 'Hello world!',
    es: '¡Hola mundo!',
    ja: 'こんにちは、世界!'
  }
};

// Usage; the prop 'greetings' will correspond to the dictionary id 'greetings' export default () => (

); // ~>

こんにちは、世界!

Valid id names: any prop except

id
,
children
,
render
and
component
since these have special meaning in React-Text. Click on those keywords to see how they are used. The ids are case-sensitive.

The dictionary can also be a function, which will be called when rendering. The advantage is that it will receive any prop that you pass to the element. You can then localize the text properly depending on the language, and even provide defaults easily:

const dictionary = {
  greetings: {
    en: ({ name = 'World' }) => `Hello ${name}!`,
    es: ({ name = 'Mundo' }) => `¡Hola ${name}!`,
    ja: ({ name = '世界' }) => `こんにちは、${name.toUpperCase()}さん!`
  }
};

// The prop passed as name will be received in the dictionary export default () => (

); // ~> こんにちは、FRANCISCOさん!

You can also use the

id
prop instead of just writing the id as a prop. These two work exactly the same:
export default () => (
  
    

);

This however works much better for dynamic ids, since those would be messy otherwise:

const key = 'greetings';

export default () => (

);

Note: the props that you can pass can be either strings or numbers, but right now you cannot pass a boolean like

. We might lift this limitation in the future.

Render

Injects the plain text into a function. Useful for those times when you can only pass plain text and not a component:

// These both render to the exact same thing:

{text}

} /> // ~>

Hello world

The next example can only be achieved with

render()
since it will pass the plain representation as specified in the dictionary:
 {text}} />
// ~> Hello world

If you try to do the same with

 you will get an unexpected result, since 
 renders a React component:
// ERROR - this does not work as expected
{<Text} />
// ~> [Object object]

Component

When trying to do a switch between more complex fragments, or display one part only for one language, we can do so by using the

component
prop:
{/* Large block of text in English here */}

)} /> {/* Large block of text in Spanish here */}

)} /> {/* Large block of text in Japanese here */}

)} />

Note that, when using

component={...}
, we are using the language as a key. This would be the internal equivalent of you doing:
// dictionary.js
// NOTE: DO NOT DO THIS, this is just a visualization of how it works internally
export default {
  en: { en: ({ component }) => component, es: '', ja: '' },
  es: { en: '', es: ({ component }) => component, ja: '' },
  ja: { en: '', es: '', ja: ({ component }) => component }
};

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.