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:


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


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.


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() {
let _ = this.context.getString
return (
{_('text1')} ๐Ÿ˜Š {_('text2')}

Was this article useful?