Language localization is an essential aspect of building user-friendly web applications. It allows users from different regions to access your website in their preferred language.
Install react-intl Package:
npm install react-intl
Configuring the Translation
To manage translations, we’ll create translation files for each supported language. In this example, we’ll start with English (en.json). Create a folder named “locales” in the root directory of your project. Inside the “locales” folder, create a file named “en.json” and add the following content:
{ "stores_tab": "Store Change.", "send_message" : "Send Message", "search_by_product": "Search by product name" }
Next, create an index.js file inside the “locales” folder. This file will serve as the entry point for importing all the translation files. Add the following code to the index.js file:
import en from './en.json'; export default {en};
Auto-Detecting the Locale ( index.js or App.js )
import { IntlProvider } from 'react-intl'; import getLocale from './utils/getLocale.js'; import translations from './locales';
To retrieve the user’s locale, create a new file named “getLocale.js” inside the “utils” folder (create the folder if it doesn’t exist). Add the following code to the “getLocale.js” file:
const getLocale = async () => { try { const response = await fetch('https://ipapi.co/json/'); const data = await response.json(); return data.country_code.toLowerCase(); } catch (error) { console.error('Error retrieving country code:', error); return null; } }; export default getLocale;
Wrap your application component with the IntlProvider component, passing the locale and messages as props:
// add useState for locale and translate message const [locale, setLocale] = useState('en'); const [message, setMessage] = useState(translations.en); // add useEffect for set local and message useEffect( async () => { async function fetchLocale() { const detectedLocale = await getLocale(); if (detectedLocale) { setLocale(translations[detectedLocale] ? detectedLocale : "en"); setMessage(translations[detectedLocale] || translations.en); } } fetchLocale(); },[]); // last application component with this IntlProvider components < IntlProvider locale={locale} messages={messages} > {/* Your application component */} < /IntlProvider >
Then, use the FormattedMessage component to wrap the text you want to translate:
import { FormattedMessage,useIntl } from "react-intl"; < FormattedMessage id="stores_tab" defaultMessage="Stores" /> // if you get message [object object] this way then use below 'useIntl' method. // or if you want to only show string inside object or inside of any pre-build component placeholder string text // add useIntl in component const intl = useIntl(); < Filters queryValue="" filters="" queryPlaceholder={intl.formatMessage({ id: 'search_by_product', defaultMessage: 'Search by product name', tagName:"" })} / > // and or object like this { "name":intl.formatMessage({ id: 'send_message', defaultMessage: 'Send Message', tagName:"" }), "data": "Success" }