In a React project, leveraging i18next and axios to translate content returned from REST API involves the following steps:
1. Setting up i18next
First, install and configure i18next in your React project. Install i18next and its React binding library react-i18next via npm or yarn.
bashnpm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector
Next, configure i18next. This is typically done in your project's entry file, such as src/index.js or src/App.js:
javascriptimport i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import HttpBackend from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; i18n .use(HttpBackend) // Load translation files .use(LanguageDetector) // Automatically detect user language .use(initReactI18next) // Bind React via react-i18next .init({ fallbackLng: 'en', // Default language debug: true, interpolation: { escapeValue: false, // No additional escaping needed } }); export default i18n;
2. Using axios to fetch REST API content
When calling the API to retrieve data, use axios. Ensure you have installed axios.
bashnpm install axios
Then, create a function to fetch articles, for example:
javascriptimport axios from 'axios'; const fetchArticles = async (language) => { try { const response = await axios.get(`https://api.example.com/articles?lang=${language}`); return response.data; } catch (error) { console.error('Fetching articles failed:', error); return []; } };
3. Combining i18next and axios
In your component, use the useTranslation hook from react-i18next to get the current language and integrate it with axios for data retrieval:
javascriptimport React, { useState, useEffect } from 'react'; import { useTranslation } from 'react-i18next'; import { fetchArticles } from './api'; const Articles = () => { const { t, i18n } = useTranslation(); const [articles, setArticles] = useState([]); useEffect(() => { const loadArticles = async () => { const fetchedArticles = await fetchArticles(i18n.language); setArticles(fetchedArticles); }; loadArticles(); }, [i18n.language]); return ( <div> <h1>{t('articles.title')}</h1> {articles.map(article => ( <div key={article.id}> <h2>{article.title}</h2> <p>{article.content}</p> </div> ))} </div> ); }; export default Articles;
4. Summary
Thus, when users change language settings (assuming you handle language switching logic elsewhere in your application), i18next notifies React components to re-render and initiates API requests in the new language context to fetch corresponding content.
This solution ensures internationalization and localization of content, dynamically displaying data based on the user's language preferences.