Traduki React helpers
npm install @traduki/react
See main github repository readme.md
- Webpack example
- Vite example
- For Webpack see the: Traduki Webpack plugin
- For Vite see the: Traduki Vite plugin
Make sure to wrap you application in the TradukiProvider:
``js
import { TradukiProvider } from '@traduki/react';
import App from './App';
render(
document.getElementById('root'),
);
`
Use the useTranslator React hook to translate messages.
`js
import { useTranslator } from '@traduki/react';
import messages from './Component.messages.yaml';
function Component() {
const t = useTranslator();
return (
{t(messages.welcome)}
export default Component;
`
Read the current locale or switch to another locale with the useLocale React hook.
`js
import { useLocale } from '@traduki/react';
import messages from './Component.messages.yaml';
function Component() {
const [locale, setLocale] = useLocale();
return (
Current locale: {locale}
export default Component;
`
Traduki is build with code splitting in mind. The preact package provides a waitForMessages function.
Use waitForMessages when using lazy to make sure the chunk's messages are also loaded before rendering the chunk's component. This is prevent a flash of unlocalized texts.
``js
// AsyncComponent.js
import { useTranslator } from '@traduki/preact';
import messages from './AsyncComponent.messages.yaml';
function AsyncComponent() {
const t = useTranslator();
return
export default Component;
// Component.js
import { lazy } from 'react';
import { waitForMessages, useTranslator } from '@traduki/react';
import messages from './Component.messages.yaml';
const AsyncComponent = lazy(() => import('./AsyncComponent').then(waitForMessages));
function Component() {
const t = useTranslator();
return (
export default Component;