Search code examples
reactjsprimereact

Display different image based on data named "countries"


I'm trying to display a different country image based on each option (which is formed by the list of countries I have - named "countries") from the "selection" but I'm not sure how to do that. How to do that?

Here is how my code looks at the moment:

import Spanish from "../../assets/country-flags/Spanish.png";
import French from "../../assets/country-flags/French.png";
...
const countries = [
    { name: "Spanish", code: "Spanish" },
    { name: "French", code: "French" },
    { name: "English", code: "English" },
    { name: "German", code: "German" },
    { name: "Italian", code: "Italian" },
    { name: "Japanese", code: "Japanese" },
    { name: "Korean", code: "Korean" },
    { name: "Russian", code: "Russian" },
    { name: "Chinese", code: "Chinese" },
  ];
const countryOptionTemplate = (option) => {
    return (
      <div className="country-item">
        <img
          alt={option.name}
          src="" <- have to change this based on the data "countries" (different flag for each option)
          onError={(e) =>
            (e.target.src =
              "https://www.primefaces.org/wp-content/uploads/2020/05/placeholder.png")
          }
          className={`flag flag-${option.code.toLowerCase()}`}
        />
        <div>{option.name}</div>
      </div>
    );
  };

The outcome should look something like this:

Desired outcome

Currently, my code makes it look like this (because the function defaults it to the placeholder image):

Current state


Solution

  • Add the image data as a key in your countries array and then use this in the render function:

    import Spanish from "../../assets/country-flags/Spanish.png";
    import French from "../../assets/country-flags/French.png";
    ...
    const countries = [
        { name: "Spanish", code: "Spanish", image: Spanish },
        { name: "French", code: "French", image: French },
        { name: "English", code: "English", image: English},
        { name: "German", code: "German", image: German},
        { name: "Italian", code: "Italian", image: Italian},
        { name: "Japanese", code: "Japanese", image: Japanese},
        { name: "Korean", code: "Korean", image: Korean},
        { name: "Russian", code: "Russian", image: Russian},
        { name: "Chinese", code: "Chinese", image: Chinese},
      ];
    const countryOptionTemplate = (option) => {
        return (
          <div className="country-item">
            <img
              alt={option.name}
              src={option.image || "https://www.primefaces.org/wp-content/uploads/2020/05/placeholder.png"} <- have to change this based on the data "countries" (different flag for each option)
              className={`flag flag-${option.code.toLowerCase()}`}
            />
            <div>{option.name}</div>
          </div>
        );
      };