Skip to content

React

First Install

Example Component

Create a FlagList.tsx component to display all flags or filter by country:

js
import React, { useState } from 'react';
import { getAllFlags, getFlagsByCountry, getFlagSvg } from 'open-flags';

const FlagList: React.FC = () => {
  const [country, setCountry] = useState('');

  const handleCountryChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setCountry(event.target.value.toLowerCase());
  };

  const flagsToDisplay = country ? getFlagsByCountry(country) : getAllFlags();

  return (
    <div>
      <h1>Flags</h1>
      <input
        type="text"
        placeholder="Enter country code"
        value={country}
        onChange={handleCountryChange}
      />
      <div>
        {flagsToDisplay.map(flag => {
          const [country, region] = flag.split('/');
          const svgContent = getFlagSvg(country, region);
          return (
            <div key={flag}>
              <h2>{flag}</h2>
              <img src={svgContent} alt='flag' />
          );
        })}
      </div>
    </div>
  );
};

export default FlagList;

Use the FlagList component in your App.tsx:

import React from 'react';
import FlagList from './FlagList';

const App: React.FC = () => {
  return (
    <div className="App">
      <FlagList />
    </div>
  );
};

export default App;