Blog>
Snippets

Setting Up TanStack Form with i18next for Internationalization

Demonstrate how to initialize TanStack Form in a JavaScript application and integrate it with i18next for dynamic language switching.
import { useForm } from 'tanstack/react-form';
import { useTranslation } from 'react-i18next';

const MyForm = () => {
  const { t } = useTranslation();
  const form = useForm({
    // Initialize your form structure here
    initialValues: {
      name: '',
      email: '',
    },
  });

  return (
    <form>
      <div>
        <label>{t('nameLabel')}</label>
        <input {...form.register('name')} />
      </div>
      <div>
        <label>{t('emailLabel')}</label>
        <input {...form.register('email')} />
      </div>
      <button type="submit">{t('submit')}</button>
    </form>
  );
};
This code snippet demonstrates initializing TanStack Form within a functional component and leveraging 'react-i18next' for dynamic language switching based on user's selection. 'useForm' is from TanStack Form for form management, and 'useTranslation' from 'react-i18next' handles the text translation.
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false,
    },
  });
This setup initializes i18next with a backend service for loading translations and a language detector to automatically detect the user's language preferences. 'initReactI18next' integrates i18next with React, enabling dynamic translations based on the current language.