synacor / preact-i18n

Simple localization for Preact.
BSD 3-Clause "New" or "Revised" License
205 stars 18 forks source link

A simpler way to pass translations to props? #36

Closed Hubro closed 4 years ago

Hubro commented 5 years ago

This might just be my opinion, but having to turn this:

<input
  type="text"
  placeholder="Email address"
  value={emailAddress}
/>

into this:

<Localizer>
  <input
    type="text"
    placeholder={
      <Text id="login-form.email-address">
        Email address
      </Text>
    }
    value={emailAddress}
  />
</Localizer>

to retrieve a translated string seems rather overkill to me. It also triggers TypeScript errors, as the placeholder prop expects a string.

Would it be possible to implement a simpler way to do this?

Something like:

const text = localizer(this.context, "login-form");

<input
  type="text"
  placeholder={text("email-address", "Email address")}
  value={emailAddress}
/>
pl12133 commented 5 years ago

@Hubro have you given the withText decorator a try? It will turn the keys into props that are all strings and thus avoid TypeScript errors.

Alternatively we could consider creating something like the localizer you mention by exposing the underlying translate function.

Hubro commented 5 years ago

@pl12133 I finally gave up and switched to React after weeks of fighting the inconsistent support of Preact X. (i.e. many of my libraries required hook support, others silently didn't work because they didn't support Preact X).

I'm now using react-i18next, and it has a hook that works pretty much exactly like my suggestion.

const { t } = useTranslation("footer");

return <div id="footer" title={ t("title", "Works with props") }>
    { t("text", "Fallback text if the translation can't be found") }
</div>;

Docs: https://react.i18next.com/guides/quick-start#using-the-hook

I would consider adding hook support, as it's much more convenient than injecting props.

pl12133 commented 5 years ago

I agree Preact X support is still spotty while it is at release candidate. We have the preactX branch and the preactX npm tag for tracking Preact X support, and those will cut over to master/latest when support becomes more widespread.

I agree we should add a hook similar to useTranslation into the Preact X branch, I would be happy to review a PR for that or work on one when I find some time and Preact X reaches stable release.

pl12133 commented 4 years ago

Going to close this out now that we have a useText hook for functional components, and a withText decorator for class components to easily convert dictionary keys into strings.