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”
JavaScript
x
35
35
1
import Afghanistan from "./CountryFlags/Afghanistan.js";
2
// condensed imports
3
4
const currencyCodeMap = {
5
AED: UnitedArabEmirates,
6
AFN: Afghanistan,
7
ALL: Albania,
8
AMD: Armenia,
9
AOA: Angola,
10
ARS: Argentina,
11
AUD: Australia,
12
AZN: Azerbaijan,
13
};
14
15
type Props = {
16
currencyCode?: string,
17
countryLabel?: string,
18
className?: string,
19
};
20
21
const CountryFlag = ({ currencyCode, countryLabel, className }: Props) => {
22
const FlagComponent = currencyCodeMap[currencyCode];
23
24
if (!FlagComponent) {
25
return <StyledIcon isOberonIcon={true} name={"countryFallback"} />;
26
}
27
28
return (
29
<StyledImageWrapper className={className}>
30
<FlagComponent />
31
</StyledImageWrapper>
32
);
33
};
34
35
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?
Advertisement
Answer
AED | "United Arab Emirates"
is not valid JavaScript syntax.
Why not have an object like:
JavaScript
1
6
1
type CountryEntry = {
2
currencyCode: string,
3
countryLabel: string,
4
flagComponent: JSX.Element
5
}
6
Then have an array of these and use .find()
to get the component.
It would look something like this:
JavaScript
1
36
36
1
import Afghanistan from "./CountryFlags/Afghanistan.js";
2
3
type Props = {
4
currencyCode?: string,
5
countryLabel?: string,
6
className?: string,
7
};
8
9
type CountryEntry = {
10
currencyCode: string,
11
countryLabel: string,
12
flagComponent: JSX.Element
13
}
14
15
const flags: CountryEntry[] = [
16
{ currencyCode: "AFN", countryLabel: "Afghanistan", flagComponent: Afghanistan },
17
/* ... */
18
];
19
20
const CountryFlag = ({ currencyCode, countryLabel, className }: Props) => {
21
const countryEntry = flags.find(
22
(f) => f.countryLabel === countryLabel || f.currencyCode === currencyCode
23
);
24
25
if (!countryEntry) {
26
return <StyledIcon isOberonIcon={true} name={"countryFallback"} />;
27
} else {
28
const FlagComponent = countryEntry.flagComponent;
29
30
return (
31
<StyledImageWrapper className={className}>
32
<FlagComponent />
33
</StyledImageWrapper>
34
);
35
};
36