Skip to main content Accessibility Feedback

<flag-emoji>

Render a country’s flag emoji from its two-letter country code.

Source Code

Usage

Include the <flag-emoji> element in your HTML. Add a [code] attribute with the two-letter country code of the flag to display as its value.

<!-- United States -->
<flag-emoji code="us"></flag-emoji>

<!-- Japan -->
<flag-emoji code="jp"></flag-emoji>

<!-- Mexico -->
<flag-emoji code="mx"></flag-emoji>

The Web Component

customElements.define('flag-emoji', class extends HTMLElement {

    /**
     * Create a new instance
     */
    constructor () {
        super();
        this.textContent = this.getFlagEmoji(this.getAttribute('code'));
    }

    /**
     * Get the flag emoji for the country
     * @link https://dev.to/jorik/country-code-to-flag-emoji-a21
     * @param  {String} countryCode The country code
     * @return {String}             The flag emoji
     */
    getFlagEmoji (countryCode) {
        let codePoints = countryCode.toUpperCase().split('').map(char =>  127397 + char.charCodeAt());
        return String.fromCodePoint(...codePoints);
    }

});

Find this useful? You can support my work by purchasing an annual membership.