Skip to main content

Internationalization

Building a bot that supports different languages requires you to separate your string literals from your components code.

First, you need to go to your src/locales folder and add a js file for each language you want to support. For example:

src/locales/en.js

export default {
text1: ['Hello!', 'Hey there!', 'Aloha'],
text2: ["What's up?", "How're you?"],
text3: ['Bye!', 'See you later', 'Ciao'],
}

src/locales/es.js

export default {
text1: ['Hola!', 'Buenas', 'Ep!'],
text2: ['Que tal?', 'Como estas?'],
text3: ['Adios', 'Hasta luego!'],
}

Locales are just javascript objects which can be defined freely, however you must have the same structure for all languages and leafs must be strings or arrays of strings. In the latter case, Botonic will choose one of the strings randomly. This makes the user feel like they're having a more natural conversation.

Now, you have to export all the languages that your bot needs.

src/locales/index.js

import en from './en'
import es from './es'

export const locales = { en, es }

In order to use these locales in your responses, you need to import the RequestContext from @botonic/react.

You can access an object from locales with the this.context.getString method. We suggest you import this.context.getString as _, as it will make your code more concise. Then you can access the string with _('stringID'), where stringID is the dotted path to access the string in you locales object.

If you want to change the language for the current user, use the method setLocale(lang).

Here is an example of a component using locales:

import React from 'react'
import { RequestContext, Text } from '@botonic/react'

export default class extends React.Component {
static contextType = RequestContext

render() {
this.context.setLocale('en')
let _ = this.context.getString
return (
<>
<Text>
{_('text1')} 😊 {_('text2')}
</Text>
<Text>{_('text3')}</Text>
</>
)
}
}
Example