skip to Main Content

Let’s say I have a list of countries that are country coded and I want to display a proper word for each code that I receive as props for my component.

interface MyComponentProps {
  countryCode: 'en' | 'de' | 'fr';
}

const MyComponent: FC<MyComponentProps> = ({countryCode}) => (
  <p>{countryCode}</p>
)

So in the component above I’d like to display for example English when I get ‘en’ as props, German for de… you get the idea. What is the best way convert these values into other values according to some map like ‘en’ = ‘English’, ‘de’ = ‘German’ etc?

2

Answers


  1. Just use an object literal:

    import React from 'react'
    
    interface MyComponentProps {
      countryCode: 'en' | 'de' | 'fr';
    }
    
    const map = {
        en: 'English',
        de: 'German',
        fr: 'French',
    } satisfies Record<MyComponentProps['countryCode'], string>
    
    const MyComponent: React.FC<MyComponentProps> = ({countryCode}) => (
      <p>{map[countryCode]}</p>
    )
    

    Playground

    Note that the satisfies clause will cause the compiler to warn you if you forget a key in the map. If you don’t want that completeness checking you can delete that bit.

    Login or Signup to reply.
  2. I personally call it "dictionary"

    const countriesDictionary = {
      'eua': 'United States',
      'fr': 'France',
      'de': 'Germany',
    };
    
    interface MyComponentProps {
      countryCode: keyof typeof countriesDictionary, // allow just valid keys in countriesDictionary
    }
    
    const MyComponent: FC<MyComponentProps> = ({countryCode}) => {
      console.log(countriesDictionary['eua']) // United States
    
      return (<p>{countriesDictionary[countryCode]}</p>)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search