Hugo Gresse
Hugo Gresse

Reputation: 17899

i18n Localization in React with Material UI by extending Typography?

I was beginning the painful job of adding the useTranslation hook of react-i18next to all my components when I thought that I could use the Typography component of MaterialUI (already in my app) to hide the logic.

➡️ Is there any recommendation/advice to do or not to do so?

➡️ Is that a good idea?

Example

import React from 'react'
import {useTranslation} from 'react-i18next'
import { Typography } from '@material-ui/core'

const TranslatedTypography = ({children}) => {
    const {t} = useTranslation()

    return <Typography>{t(children)}</Typography>
}

Upvotes: 3

Views: 6773

Answers (1)

Hugo Gresse
Hugo Gresse

Reputation: 17899

It does not fit every use case (for example for a button text where the hook is used) but here is what I've used:

import { Trans } from 'react-i18next'
import { Typography } from '@material-ui/core'
import React from 'react'

const TranslatedTypography = ({
    children,
    i18nKey,
    count = 1,
    ...otherProps
}) => {
    return (
        <Typography {...otherProps}>
            <Trans i18nKey={i18nKey} count={count}>
                {children}
            </Trans>
        </Typography>
    )
}

export default TranslatedTypography

And you can use it as follow:

<TranslatedTypography
    i18nKey="yourKey"
    variant="h6">
  title
</TranslatedTypography>

Note: it seems you can also omit the i18nKey prop and put the key directly as the children.

Upvotes: 2

Related Questions