Skip to content

Frontend: Translation Guide

Tom Robinson edited this page Jun 18, 2019 · 1 revision

Here's a quick run down on how to modify a component so its strings will be available for translation.

Here's an example React component that has yet to be translated.

class TranslateMe extends Component {
  render () {
    const { name } = this.props
    return (
       <div>
         <h1>Greetings translator!</h1>
         <p>Thanks for helping translate Metabase {{name}}</p>
       </div>
    )
  }
}

To make sure the strings are added to the inventory of strings to be translated, we need to add tags. That same component when prepared for translation now looks like this.

class TranslateMe extends Component {
  render () {
    const { name } = this.props
    return (
       <div>
         <h1>{t`Greetings translator!`}</h1>
         <p>{t`Thanks for helping translate Metabase ${name}`}</p>
       </div>
    )
  }
}

You'll note we didn't have to explicitly import t. It's available as a global so that it can be used in any .js or .jsx file.

The concept is almost exactly the same when the strings you need to translate live in a data structure instead of inside a JSX tag.

This:

const stringsToTranslate = [
  { greeting: 'Hello' },
  { greeting: 'Hi' },
  { greeting: 'Nice to meet you' },
]

Becomes:

const stringsToTranslate = [
  { greeting: t`Hello` },
  { greeting: t`Hi` },
  { greeting: t`Nice to meet you` },
]

One subtle but important thing to note is that in the conversion we're no longer using ' and instead we're using es2015 template literals (`).

In certain cases where more complex JSX nesting is occurring things work similarly but with a couple important caveats.

Take the following example:

render () {
  return (
    <div><strong>{this.props.name}</strong> has a cool <b>accented</b> name.</div>
  )
}

Because of the nested and tags we can't use just t cause those would be interpreted as plain text and not the actual JSX markup that they are.

In this case we can use jt to take the extra markup into account.

render () {
  return (
    <div>${ jt`${<strong>{this.props.name}</strong>} has a cool ${<b>t`accented`</b>} name.` }</div>
  )
}

That's all there is to it. Thanks for being interested in contributing to Metabase. If you need further guidance we recommend you look at existing translated components in the source code for examples.

Clone this wiki locally