Published on

Country Flags API: Use This in Your Application

Authors
  • avatar
    Name
    Jeremy Persing
    Twitter

Introduction

Head to countryflagsapi.com where you can get any country flag by the country's name, UN code, ISO Alpha-3 code, or ISO ALpha-2 code. If you have any suggestions on what I should add there's a suggestion box on the website.

Getting a Flag from User Input

I'll be using React for this demo. Keep in mind this is a basic demo, but this will probably be similar to what you will want to use in your app.

Imports

import React, { useState } from 'react'

States and Functions

const [flagURL, setFlagURL] = useState('https://countryflagsapi.com/png/cuba')
const [identifier, setIdentifier] = useState('')

const handleButtonClick = () => {
  // can use https://countryflagsapi.com/svg/ here too
  const url = 'https://countryflagsapi.com/png/'
  setFlagURL(url + identifier)
}

JSX

<div style={{ marginBottom: '20px' }}>
    <input
      name="country"
      type="text"
      onChange={(e) => setIdentifier(e.target.value)}
      value={identifier}
      placeholder="Enter a country name, UN Code, ISO Alpha-2, or ISO Alpha-3 Code"
    />
    <button onClick={handleButtonClick}>Get Flag</button>
</div>
<img src={flagURL} alt="flag" />

Embedding an Image

Go to the flag that you want to embed and click the button labeled "Embed SVG" or "Embed PNG". A modal will then appear like the one shown in the image below. Go ahead and click copy and then paste the img element into your source code.

Modal