I have a React component which accepts 3 props:
And makes use of a flagsList like so:
type CountryEntry = {
currencyCode?: string,
countryCode?: string,
countryLabel: string,
flagComponent: JSX.Element,
};
export const flagsList: CountryEntry[] =
{
currencyCode: "AED",
countryCode: "AE",
countryLabel: "United Arab Emirates (the)",
flagComponent: UnitedArabEmirates,
},
{
currencyCode: "AFN",
countryCode: "AF",
countryLabel: "Afghanistan",
flagComponent: Afghanistan,
},
];
What I am trying to do is:
true - search the flagsList by currencyCode, andtrue search the flagsList by countryCodewhilst maintaining the fallback for each if a code cannot be found (StyledIcon)
const CountryFlag = ({ code, currencyCode, countryCode }: Props) => {
const countryEntry = flagsList.find(
(f) => f.currencyCode === currencyCode
);
if (!countryEntry) {
return <StyledIcon name={"countryFallback"} />;
} else {
const FlagComponent = countryEntry.flagComponent;
return (
<StyledImageWrapper className={className}>
<FlagComponent />
</StyledImageWrapper>
);
}
};
Consider using a string union or enum instead of multiple booleans.
type CountryFlagProps = {
keyCode: string;
keyType: "currencyCode" | "countryCode";
};
const CountryFlag = ({ keyCode, keyType }: CountryFlagProps) => {
const countryEntry = flagsList.find((f) => f[keyType] === keyCode);
if (countryEntry) {
return countryEntry.flagComponent
}
// Choose your fallback
return <Flag country="UK" />;
};
If you know all of your codes in advance you can be more restrictive and consumers will get better intellisense when using <CountryFlag />
type CurrencyCode = "AED" | "AFN";
type CountryCode = "AE" | "AF";
type CountryEntry = {
currencyCode?: CurrencyCode;
countryCode?: CountryCode;
countryLabel: string;
flagComponent: JSX.Element;
};
const flagsList: Array<CountryEntry> = [
{
currencyCode: "AED",
countryCode: "AE",
countryLabel: "United Arab Emirates (the)",
flagComponent: <Flag country="AE" />
},
{
currencyCode: "AFN",
countryCode: "AF",
countryLabel: "Afghanistan",
flagComponent: <Flag country="AF" />
}
];
type CountryFlagProps = {
keyCode: CurrencyCode | CountryCode;
keyType: "currencyCode" | "countryCode";
};
const CountryFlag = ({ keyCode, keyType }: CountryFlagProps) => {
const countryEntry = flagsList.find((f) => f[keyType] === keyCode);
if (countryEntry) {
return countryEntry.flagComponent;
}
return <Flag country="UK" />;
};
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<CountryFlag keyCode="AF" keyType="countryCode" />
</div>
);
}