Get the country flag from the country code in React
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
Steps to get the country flag in React
1. Install npm dependency in React app
Let’s install the flag-icon-css npm package by running the following command.
1 | 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.
1 | import 'flag-icon-css/css/flag-icon.min.css'; |
Now simply use the CSS class to display the flag icon. For example,
1 2 3 4 5 | // USA <span classname="flag-icon flag-icon-us"></span> // INDIA <span classname="flag-icon flag-icon-in"></span> |
Look at the simple example where we will render the flags from the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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}" classname="box"> <span classname="{`flag-icon" flag-icon-${x.code}`}=""></span> <div classname="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..!! 🙂