axel
axel

Reputation: 4137

How to use <Trans /> of react-i18next for an alt image translation?

I've an issue that should be (hopefully) simple to solve. I've installed react-i18next in my project and all works fine, I am able to have translations in Functional components, in classes, but my only issue now is in a class component, specifically regarding an html attribute, I'm talking about the alt of an image.

// ...
import { Translation, Trans } from 'react-i18next'

class MyComponent extends Component<MyComponentProps, MyComponentState> {
  constructor(props: MyComponentProps) {
    super(props)

    this.state = {
      isButtonVisible: true,
      isAnimationVisible: false,
      deadline: 0,
      countdown: ''
    }

    // ...
  }

  // ...

  render () {
    const { isButtonVisible, isAnimationVisible, deadline } = this.state

    return (
      <>
        <Trans>
          <img className={styles.exercise} src={lungs} alt={`${t('animation.lungs')} IDXXX`}  />
        </Trans>
      <>
    )
  }
}

where animation.lungs is my translations in locales file and IDXXX is a numeric id that does not require any translation.

The t is not defined and it makes sense, but documentation here is not clear https://react.i18next.com/legacy-v9/trans-component for me. Do you have any ideas how to fix it?

Thanks in advance

Upvotes: 0

Views: 1608

Answers (1)

Sagi Rika
Sagi Rika

Reputation: 2979

You can import the withTranslation HOC in order to get access to t().

import { Translation, Trans, withTranslation, WithTranslation } from 'react-i18next'

type MyComponentProps = {} & WithTranslation

class MyComponent extends Component<MyComponentProps, MyComponentState> {
  constructor(props: MyComponentProps) {
    super(props)

    this.state = {
      isButtonVisible: true,
      isAnimationVisible: false,
      deadline: 0,
      countdown: ''
    }

    // ...
  }

  // ...

  render () {
    const { isButtonVisible, isAnimationVisible, deadline } = this.state
    const { t } = this.props;

    return (
      <>
        <Trans>
          <img className={styles.exercise} src={lungs} alt={`${t('animation.lungs')} IDXXX`}  />
        </Trans>
      <>
    )
  }
}

export default withTranslation()(MyComponent)

Upvotes: 1

Related Questions