@traduki/preact
TypeScript icon, indicating that this package has built-in type declarations

0.11.0 • Public • Published

@traduki/preact

npm

See main github repository readme.md

Examples

Install

Usage

<TradukiProvider />

Make sure to wrap you application in the TradukiProvider:

import { TradukiProvider } from '@traduki/preact';
import App from './App';

render(
    <TradukiProvider initialLocale="en">
        <App />
    </TradukiProvider>
    document.getElementById('root'),
);

useTranslator

Use the useTranslator hook to translate messages.

import { useTranslator } from '@traduki/preact';
import messages from './Component.messages.yaml';

function Component() {
    const t = useTranslator();

    return (
        <div>
            <p>{t(messages.welcome)}</p>
        </div>
    );
}

export default Component;

useLocale

Read the current locale or switch to another locale with the useLocale hook.

import { useLocale } from '@traduki/preact';
import messages from './Component.messages.yaml';

function Component() {
    const [locale, setLocale] = useLocale();

    return (
        <div>
            <p>Current locale: {locale}</p>
            <p>
                <button onClick={() => setLocale('en-US')}>en</button>
                <button onClick={() => setLocale('nl-NL')}>nl</button>
            </p>
        </div>
    );
}

export default Component;

waitForMessages

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.

// AsyncComponent.js
import { useTranslator } from '@traduki/preact';
import messages from './AsyncComponent.messages.yaml';

function AsyncComponent() {
    const t = useTranslator();

    return <div>{t(messages.hello)}</div>;
}

export default Component;


// Component.js
import { lazy } from 'preact/compat';
import { waitForMessages, useTranslator } from '@traduki/preact';
import messages from './Component.messages.yaml';

const AsyncComponent = lazy(() => import('./AsyncComponent').then(waitForMessages));

function Component() {
    const t = useTranslator();

    return (
        <div>
            <Suspense fallback={<div>{t(messages.loading)}</div>}>
                <AsyncComponent />
            </Suspense>
        </div>
    );
}

export default Component;

Package Sidebar

Install

npm i @traduki/preact

Weekly Downloads

7

Version

0.11.0

License

MIT

Unpacked Size

14.7 kB

Total Files

11

Last publish

Collaborators

  • havelaer