Adding a language switcher to a React app is a great way to enhance user experience and make your app more accessible to a wider audience. It's important to note that relying solely on the user's preferred language from the browser may not always be the best approach. For example, if your app targets users who are not native speakers of their browser's language, they may prefer to use a different language in your app. Additionally, some users may simply prefer to use a language other than their browser's default language.
Here's an example of how you can add a language switcher to a React app using the react-intl library for localization. Keep in mind that other localization libraries would require a similar solution.
function LocalizationWrapper() {
const [locale, setLocale] = useState(initLocale);
const [messages, setMessages] = useState(null);
useEffect(() => loadMessages(locale).then(setMessages), [locale]);
return messages ? (
<IntlProvider locale={locale} messages={messages}>
<App locale={locale} direction={getDirection(locale)} onLocaleChange={(locale) => setLocale(locale)} />
</IntlProvider>
) : null;
}
function App({ locale, direction, onLocaleChange }) {
const intl = useIntl();
return (
<div>
<div style={{ textAlign: "center" }}>
<select value={locale} onChange={(e) => onLocaleChange(e.target.value)}>
<option value="en">en</option>
<option value="es-MX">es-MX</option>
<option value="ar">ar</option>
</select>
</div>
<div dir={direction}>
{intl.formatMessage({ id: "common.welcome" })}
</div>
</div>
);
}