A
A
Alexander2021-03-29 11:16:39
JavaScript
Alexander, 2021-03-29 11:16:39

How to dynamically substitute icons for object keys?

An object comes from the server

"contacts": {
                    facebook: "",
                    github: "",
                    instagram: "",
                    mainLink: null,
                    twitter: "",
                    vk: "",
                    website: null,
                    youtube: null
                }
, you need to substitute the material ui icon for each key, how can this be done? I will be grateful for the answer

Source code now
{Object.keys(profile.contacts).map((key) => {
                return (
                  <Contact
                    key={key}
                    contactTitle={key}
                    contactLink={
                      <a target='_blank' rel='profile' href={`${profile.contacts[key as keyof ContactsType]}`}>
                        {profile.contacts[key as keyof ContactsType]}
                      </a>
                    }
                  />
                )
              })}


const Contact: React.FC<ContactPropsType> = ({ contactTitle, contactLink }) => {
  return (
    <div>
      <span>
        {contactTitle}: {contactLink}
      </span>
    </div>
  )
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shading, 2021-03-29
@axrising

Are you creating a function that returns the material UI component to you by key?

getIcon = key => {
  switch(key) {
      case: 'facebook': 
         return {
              <MaterialUiComponent {...rest} />
         }
   }
}



const Contact: React.FC<ContactPropsType> = ({ key, contactTitle, contactLink }) => {
  return (
    <div>
      <span>
        {getIcon(key)}
        {contactTitle}: {contactLink}
      </span>
    </div>
  )
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question