Search code examples
javascriptreactjslodash

Mapping a different icon depending on property value in React


https://codesandbox.io/s/r546o8v0kq

My above sandbox shows basic mapping of an array of items. This forms a list of notes, dates and an icon depending on what type of item it is.

I am working some logic that maps each item to find out what value it is, based on that I assign the value a string to complete the type of font awesome logo.

const noteType = _.uniq(notes.map(value => value.intelType));
const noteIcon = [
  `${noteType}`.toUpperCase() == "EDUCATION"
    ? "paper-plane"
    : `${noteType}`.toUpperCase() == "ELIGIBILITY"
    ? "heart"
    : `${noteType}`.toUpperCase() == "GENERAL"
    ? "twitter"
    : null
];

If "intelType" has a value of "education" it would return the "paper-plane" string to complete the icon. e.g fa fa-${noteIcon}

    <List>
      {notes.map((note, index) =>
        note !== "" ? (
          <React.Fragment>
            <ListItem className="pl-0">
              <i class={`fa fa-${noteIcon}`} aria-hidden="true" />
              <ListItemText
                secondary={moment(note.createdAt).format("DD-MMM-YYYY")}
              />
            </ListItem>
            <p>{note.note}</p>
            <Divider />
          </React.Fragment>
        ) : null
      )}
    </List>

Its not getting mapped and returning all three values, which does not meet any criteria therefore returns null as requested. I'm a bit stuck as what to do next here.


Solution

  • You can define an object that maps intel type to icon names:

    const noteIconMap = 
          { "EDUCATION": "paper-plane",
            "ELIGIBILITY": "heart",
            "GENERAL": "twitter",
          };
    

    And look it up this way inside the render:

    <i class={`fa fa-${noteIconMap[note.intelType.toUpperCase()]}`} aria-hidden="true" />
    

    Although, beware, if there is a case where note can have intelType undefined, toUpperCase call will throw an error.

    Here's a link to working modified sandbox: https://codesandbox.io/s/ojz2lzz03z