Clue Mediator

Get the country flag from the country code in React

📅June 17, 2021

Today we will show you how to get the country flag from the country code in React.

In this example, we will use the flag-icon-css to get the country flag icon in SVG format by passing the country code.

Checkout more articles on ReactJS

Demo Application

Get the country flag from the country code in React - Clue Mediator

Get the country flag from the country code in React - Clue Mediator

Steps to get the country flag in React

  1. Install npm dependency in React app
  2. Add logic to get the country flag
  3. Output

1. Install npm dependency in React app

Let’s install the flag-icon-css npm package by running the following command.

npm i flag-icon-css

2. Add logic to get the country flag

First of all, we have to import the flag icon css at the top of the component. Import the following css link.

import 'flag-icon-css/css/flag-icon.min.css';

Now simply use the CSS class to display the flag icon. For example,

// USA
<span class="flag-icon flag-icon-us"></span>

// INDIA
<span class="flag-icon flag-icon-in"></span>

Look at the simple example where we will render the flags from the array.

import React from 'react';
import 'flag-icon-css/css/flag-icon.min.css';

const countryList = [
  { name: 'USA', code: 'us' },
  { name: 'INDIA', code: 'in' },
  { name: 'UK', code: 'gb' }
]

function App() {
  return (
    <div>
      <h3>Get the country flag from the country code in React</h3>
      {countryList.map((x, i) => {
        return <div key={i} class="box">
          <span class="{`flag-icon" flag-icon-${x.code}`}=""></span>
          <div class="title">{x.name}</div>
        </div>
      })}
    </div>
  );
}

export default App;

3. Output

Run the application and check the output in the browser.

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project