Skip to content

Instantly share code, notes, and snippets.

@geberl
Created November 8, 2018 13:48
Show Gist options
  • Save geberl/5d0eb57cc1b39ec26d93468e98f7d338 to your computer and use it in GitHub Desktop.
Save geberl/5d0eb57cc1b39ec26d93468e98f7d338 to your computer and use it in GitHub Desktop.
React component to get the unicode flag character for a country code; doesn't work on Windows because the flag symbols are missing there
import React from "react"
export default class CountryFlag extends React.PureComponent {
constructor(props) {
super(props)
this.state = {
countryCode: props.countryCode ? props.countryCode : "???",
fontSize: props.fontSize ? props.fontSize : 24
}
}
/**
* @param {String} countryCode
* @returns {String}
*/
getFlacCharacter(countryCode) {
// Source: https://github.com/thekelvinliu/country-code-emoji/blob/master/src/index.js
const offset = 127397
if (typeof countryCode !== "string") throw new TypeError("argument must be a string")
const cc = countryCode.toUpperCase()
return /^[A-Z]{2}$/.test(cc) ? String.fromCodePoint(...[...cc].map(c => c.charCodeAt() + offset)) : null
}
render() {
const { countryCode, fontSize } = this.state
const style = {
fontSize: fontSize
}
return <span style={style}>{countryCode == "???" ? "❓" : this.getFlacCharacter(countryCode)}</span>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment