Aiwatar da Ƙasashen Duniya(i18n) a cikin Next.js: Multilingual

A cikin wannan sashe, za mu jagorance ku ta hanyar aiwatar da Internationalization(i18n) a cikin Next.js aikace-aikacenku. Tare da i18n, zaku iya ƙirƙirar ƙwarewar harshe da yawa don masu amfani da samar da takamaiman abun ciki na harshe.

Amfani da next-i18next Library

next-i18next sanannen ɗakin karatu ne don aiwatar da i18n a Next.js aikace-aikace. Ga yadda zaku iya ƙara i18n zuwa aikace-aikacen ku:

Shigar next-i18next:

npm install next-i18next

Sanya ɗakin karatu a cikin next.config.js fayil ɗin ku:

const { i18n } = require('./next-i18next.config');  
  
module.exports = {  
  i18n,  
};  

Ƙirƙiri fayil ɗin daidaitawa mai suna next-i18next.config.js:

module.exports = {  
  i18n: {  
    locales: ['en', 'fr', 'es'],  
    defaultLocale: 'en',  
  },  
};  

Yi amfani da ɗakin karatu a cikin aikace-aikacenku:

import { useTranslation } from 'next-i18next';  
  
function MyComponent() {  
  const { t } = useTranslation();  
  
  return( 
    <div>  
      <p>{t('welcome')}</p>  
    </div>  
 );  
}  

Ƙirƙirar Abun Cikin Harsuna da yawa

Bayan shigar next-i18next, zaku iya ƙirƙirar fayilolin harshe kamar en.json, fr.json, es.json don samar da abun ciki a cikin kowane harshe:

// en.json  
{  
  "welcome": "Welcome!"  
}  
  
// fr.json  
{  
  "welcome": "Bienvenue!"  
}  
  
// es.json  
{  
  "welcome": "¡Bienvenido!"  
}  

Canja Harshe

Don ba da damar sauya harshe, zaku iya ƙirƙirar kayan aikin sauya harshe kuma kuyi amfani da i18n.changeLanguage aikin:

 

import { useTranslation } from 'next-i18next';  
  
function LanguageSwitcher() {  
  const { i18n } = useTranslation();  
  
  const handleChangeLanguage =(newLanguage) => {  
    i18n.changeLanguage(newLanguage);  
  };  
  
  return( 
    <div>  
      <button onClick={() => handleChangeLanguage('en')}>English</button>  
      <button onClick={() => handleChangeLanguage('fr')}>Français</button>  
      <button onClick={() => handleChangeLanguage('es')}>Español</button>  
    </div>  
 );  
}  

Kammalawa

Wannan sashe ya gabatar da ku ga tsarin aiwatar da Internationalization(i18n) a cikin Next.js aikace-aikacenku ta amfani da next-i18next ɗakin karatu. Ta hanyar samar da takamaiman abun ciki na harshe da baiwa masu amfani damar canza yaruka, zaku iya ƙirƙirar ƙwarewar yaruka da yawa ga masu amfani da ku.