Skip to content

Mapping through multiple possible values in an object – React component

I currently have a component that takes a currencyCode and returns an SVG of the corresponding country. I want to expand the component for instances whereby we want to search by country name and not by currency code. The current props that are passed into the component are:

currencyCode – which is something like “AED” & countryLabel – which is something like “United Arab Emirates”

import Afghanistan from "./CountryFlags/Afghanistan.js";
// condensed imports

const currencyCodeMap = {
  AED: UnitedArabEmirates,
  AFN: Afghanistan,
  ALL: Albania,
  AMD: Armenia,
  AOA: Angola,
  ARS: Argentina,
  AUD: Australia,
  AZN: Azerbaijan,
};

type Props = {
  currencyCode?: string,
  countryLabel?: string,
  className?: string,
};

const CountryFlag = ({ currencyCode, countryLabel, className }: Props) => {
  const FlagComponent = currencyCodeMap[currencyCode];

  if (!FlagComponent) {
    return <StyledIcon isOberonIcon={true} name={"countryFallback"} />;
  }

  return (
    <StyledImageWrapper className={className}>
      <FlagComponent />
    </StyledImageWrapper>
  );
};

I tried to update my currencyCodeMap to something like:

AED | "United Arab Emirates" so that either the label or the code would return a flag, but no joy. Any suggestions?

Answer

AED | "United Arab Emirates" is not valid JavaScript syntax.

Why not have an object like:

type CountryEntry = {
  currencyCode: string,
  countryLabel: string,
  flagComponent: JSX.Element
}

Then have an array of these and use .find() to get the component.

It would look something like this:

import Afghanistan from "./CountryFlags/Afghanistan.js";

type Props = {
  currencyCode?: string,
  countryLabel?: string,
  className?: string,
};

type CountryEntry = {
  currencyCode: string,
  countryLabel: string,
  flagComponent: JSX.Element
}

const flags: CountryEntry[] = [
  { currencyCode: "AFN", countryLabel: "Afghanistan", flagComponent: Afghanistan },
/* ... */
];

const CountryFlag = ({ currencyCode, countryLabel, className }: Props) => {
  const countryEntry = flags.find(
    (f) => f.countryLabel === countryLabel || f.currencyCode === currencyCode
  );

  if (!countryEntry) {
    return <StyledIcon isOberonIcon={true} name={"countryFallback"} />;
  } else {
    const FlagComponent = countryEntry.flagComponent;
    
    return (
      <StyledImageWrapper className={className}>
        <FlagComponent />
      </StyledImageWrapper>
    );
};