Home > Net >  Using dynamic img src from an imported image
Using dynamic img src from an imported image

Time:09-24

I am using React for this. Basically, I have imported three social media images. Twitter, Facebook and Pinterest which are just svg's.

I am recieving data from a CMS backend which is just a string for the social media selected which comes back as just a string.

So, When I render for example, {link.social_media}, I recieve back 'facebook'.

I want to render the facebook image if I get the 'facebook' string from {link.social_media}, twitter image if I get 'twitter' back etc.

But, I can't figure out why this is not working, can somebody help me?

import React from "react";
import twitter from "../images/socials/twitter.svg";
import pinterest from "../images/socials/pinterest.svg";
import facebook from "../images/socials/facebook.svg";

const SocialDivider = ({ links, alignLeft }) => {
  return Array.isArray(links) ? (
    <div className="generic-block-container">
      <div
        className="socials-footer"
        style={{
          justifyContent: alignLeft ? "flex-start" : "",
        }}
      >
        {Array.isArray(links) &&
          links.map((link) => {
            let selectedSocial = link.social_media;
            console.log(selectedSocial);
            // Say for example, this returns 'facebook'


            return (
              <a className="socials-footer__item" href={link.url}>
                <img src={{ selectedSocial }} />
                {/* This image should render the 'facebook' imported image */}

                
              </a>
            );
          })}
      </div>
    </div>
  ) : (
    <></>
  );
};

export default SocialDivider;

CodePudding user response:

You can use conditional rendering as selectedSocial will output a string:

  const getSocialImage = (selectedSocial) => {
    let socialImage = twitter;
    socialImage = selectedSocial === "twitter" ? twitter : socialImage;
    socialImage = selectedSocial === "pinterest" ? pinterest : socialImage;
    socialImage = selectedSocial === "facebook" ? facebook : socialImage;

    return <img src={socialImage} alt="Social Icon" />;
  }

Then in render function:

<a className="socials-footer__item" href={link.url}>
   {getCardImage(selectedSocial)}
</a>
  • Related