Sisky
Sisky

Reputation: 603

Using i18next to replace a variable with a ReactNode element

I have a translation json file with the following translation:

"pageNotFound": {
  "description": "The page could not be found. Click {{link}} to return to the home page"
},

The link variable I am wanting to be replaced by a ReactRouter <Link>

I have the following code in my render method which outputs the below picture.

public render() {

  const { t } = this.props;
  const message = t('pageNotFound.description', { link: <Link to="/">here</Link> });

  return (
    <div className="body-content">
      <div>
        {message}
      </div>
    </div>
  );
}

Translation empty

I have played with the <Trans> component and I think this may be a way but it seems like you have to type the full text including <> tags which for my use case is not what i'm after as I want all text to be in the translation json if possible.

Any recommendations are welcome

Upvotes: 7

Views: 2116

Answers (1)

felixmosh
felixmosh

Reputation: 35573

You should use Trans component for this.

"pageNotFound": {
  "description": "The page could not be found. Click <0>here</0> to return to the home page"
},
public render() {
  const { t } = this.props;

  return (
    <div className="body-content">
      <div>
        <Trans
          t={t}
          i18nKey="pageNotFound.description"
          components={[
            <Link key={0} to="/">
              here
            </Link>,
          ]}
        />
      </div>
    </div>
  );
}

Upvotes: 8

Related Questions