jlarmstrongiv / astro-i18n-aut

The i18n integration for Astro 🧑‍🚀
https://www.npmjs.com/package/astro-i18n-aut
MIT License
125 stars 12 forks source link

jsx/tsx support #15

Closed tiwka19 closed 1 year ago

tiwka19 commented 1 year ago

is there any way to translate a jsx component? If not, will there be such an opportunity in the future?

jlarmstrongiv commented 1 year ago

You can pass the translated content title={t('title')} or locale locale={locale} as props to JSX components.

One complication is context or other global state wrappers may not work with Astro islands.

Translations usually live in a separate place like json files or databases, not in frontend components.

tiwka19 commented 1 year ago

You can pass the translated content title={t('title')} or locale locale={locale} as props to JSX components.

One complication is context or other global state wrappers may not work with Astro islands.

Translations usually live in a separate place like json files or databases, not in frontend components.

Sorry, but could you please show an example? How to pass the current locale to a jsx component? Because getLocale(Astro.url) won't work. Sorry for stupid questions, I'm a newbie

jlarmstrongiv commented 1 year ago

I encourage you to read through:

---
import { getLocale } from "astro-i18n-aut";
import Layout from '../layouts/MyLocaleLayout.tsx';
import { DEFAULT_LOCALE } from "../consts";

const locale = getLocale(Astro.url) ?? DEFAULT_LOCALE;
---

<Layout locale={locale} />

The ?? DEFAULT_LOCALE is needed because we can’t parse the DEFAULT_LOCALE from a url that does not contain the locale. See https://github.com/jlarmstrongiv/astro-i18n-aut/blob/main/src/edge-runtime/getLocale.ts#L2

Or, in your Layout component, you can make the locale prop optional and default it to the DEFAULT_LOCALE. It just depends on which works better for your setup.