React integration for backend-friendly i18n
npm install @bf-i18n/react


React integration for bf-i18n. Provides hooks, components, and HOC to use Rails/Laravel translation formats in your React applications.
Part of the bf-i18n project.
``bash`
npm install @bf-i18n/react
- React context provider
- Hooks for translations and locale management
- Trans component for JSX-based translations
- HOC for class components
- Reactive locale updates
`tsx
import { createI18n } from '@bf-i18n/core';
import { I18nProvider } from '@bf-i18n/react';
const i18n = createI18n({
defaultLocale: 'en',
mode: 'rails',
translations: {
en: {
greeting: 'Hello, %{name}!',
items: {
one: '1 item',
other: '%{count} items',
},
},
},
});
function App() {
return (
);
}
`
`tsx
import { useTranslation } from '@bf-i18n/react';
function MyComponent() {
const { t, locale, setLocale } = useTranslation();
return (
{t('greeting', { name: 'React' })}
{t('items', { count: 5 })}
Current locale: {locale}
$3
`tsx
import { useLocale } from '@bf-i18n/react';function LocaleSwitcher() {
const { locale, setLocale, availableLocales } = useLocale();
return (
);
}
`$3
`tsx
import { useI18n } from '@bf-i18n/react';function DebugComponent() {
const i18n = useI18n();
return (
{JSON.stringify(i18n.getMissingKeys(), null, 2)}
);
}
`$3
`tsx
import { Trans } from '@bf-i18n/react';function Welcome() {
return (
i18nKey="greeting"
values={{ name: 'React' }}
/>
);
}
`$3
`tsx
import { withTranslation, WithTranslationProps } from '@bf-i18n/react';interface Props extends WithTranslationProps {
name: string;
}
class Greeting extends React.Component {
render() {
const { t, name } = this.props;
return {t('greeting', { name })}
;
}
}
export default withTranslation(Greeting);
`API
$3
-
I18nProvider - Context provider
- Trans - Translation component$3
-
useTranslation() - Returns { t, locale, setLocale }
- useLocale() - Returns { locale, setLocale, availableLocales }
- useI18n() - Returns the I18n instance$3
-
withTranslation(Component) - Injects t, locale, setLocale` propsMIT