Reputation: 163
I have a multilingual reactjs app and I want a flag icon to match with a language code when I change language, how to do it without having to upload each flag manually?
Upvotes: 1
Views: 4994
Reputation: 1
You can't, as language and country are not directly related.
You can't deduce the language just by looking at the country, and viceversa. Because not every country has only one language, and not every language is spoken in only one country. Otherwise you will end up with a canadian flag for French, an australian flag for English, a spanish flag for Catalan, and a swiss flag that could be any. All of them wrong.
Upvotes: 0
Reputation: 44088
Note, Windows only displays flag unicode characters as two letters unless the browser is Firefox (see article), so in order to cover for Windows and any browser, use a library. The example below uses emoji.css. Details are commented in the example.
/**
* This will change the class of a given element to that of a given
* two letter country code. emoji.css must be loaded and the classList
* of the element must include "em" and "em-flag-[country code]"
* @param {string} selector - CSS selector of element
* @param {string} country - Two letter country code
*/
function setFlag(selector, country) {
// Reference the element
const tag = document.querySelector(selector);
/* If country is two letters return it in lower case, otherwise
* return the last two letters of the browser default language.
*/
const cty = /[A-Za-z]{2}/.test(country) ? country.toLowerCase() : navigator.language.slice(-2).toLowerCase();
// Remove "em-flag-..." from classList.
tag.className = tag.className.replace(/em-flag-\w{2}/g, "");
// Add "em-flag-[cty]" to classList
tag.classList.add(`em-flag-${cty}`);
}
// For demonstration purposes
document.querySelector("input").oninput = e => {
setFlag(".em", e.target.value);
}
<!--| Flag Icons
This stylesheet provides the flag icons.
For details, go to:
https://afeld.github.io/emoji-css/
-->
<link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">
<label>Enter a two letter Country Code:
<input style="display:inline-block;width:2ch;text-align:center">
</label>
<i class="em"></i>
Upvotes: 1
Reputation: 1493
You can try using some library, like country-flag-icons.
import * as Flags from 'country-flag-icons/react/3x2'
const Flag = Flags[value];
<Flag title={value} className="..."/>
Upvotes: 2