Search code examples
reactjsvisual-studio-codeprettieri18next

React + i18next + Trans + Prettier: Prettier eventually destroys translations when reformatting JSX


I have a react project using i18next for translations. My Visual Studio Code also runs "Prettier" to make my code look more beautiful :-)

In some cases I need to use the <Trans> component in order to be able to translate texts containing HTML/JSX markup

So this works perfectly:

<Trans i18nKey="msg_new_user_register">
  New user - please <Link to="/register">register</Link>
</Trans>

with this in translation.json

"msg_new_user_register": "New user - please <1>register</1>",

But now I needed to add the state property to the Link. After doing this, Prettier strikes back and reformats the string to

<Trans i18nKey="msg_new_user_register">
  New user - please{" "}
  <Link
    to="/register"
    state={
      location.state
        ? { from: { pathname: location.state.from.pathname } }
        : null
    }
  >
    register
  </Link>
</Trans>

even though I wrote everything in one line. In this case, the translation is only showing the text before the Link and the Link itself is completely ignored.

Is there any way to work around? Can Prettier be specifically asked to ignore JSX "one-liners" when reformatting?

Can i18next Trans be made more tolerant?


Solution

  • I found it out myself ...

    <Trans> has an alternative way of stating the default value (other than using the children):

    <Trans
      i18nKey="msg_new_user_register"
      defaults="New user - please <mylink>register</mylink>"
      components={{
        mylink: (
          <Link
            to="/register"
            state={
              location.state
                ? { from: { pathname: location.state.from.pathname } }
                : null
            }
          >
            DUMMY
          </Link>
        ),
      }}
    />
    

    with this in translation.json:

    "msg_new_user_register": "New user - please <mylink>register</mylink>",
    

    It will show the rendered element no matter how Prettier reformats it.