Next.js Discord

Discord Forum

Pass an image based on variable variable

Unanswered
Lithuanian Hound posted this in #help-forum
Open in Discord
Lithuanian HoundOP
How can I pass a variable from a variable to a property?
import facebook from "/src/images/facebook.svg";
import twitch from "/src/images/twitch.svg";
import twitter from "/src/images/twitter.svg";


    const socialLinkItems: { [key: string]: string } = {
        twitter: "https://twitter.com",
        facebook: "https://www.facebook.com/",
        twitch: "http://www.twitch.tv",
    };

...

    const socialLinks = Object.keys(socialLinkItems).map((title, index) => {
        return (
            <Image src={title} />
        )
    }

Where the title references each of those images in turn?

7 Replies

Asian black bear
You can put the images in an object like the url strings then reference it with [] notation
Lithuanian HoundOP
Ah, that's a good idea, thanks!
Asian black bear
Or even wrap them in an object with the urls in the current mapping object, then you can get them for free in the .map
Lithuanian HoundOP
Sorry, not sure I understand that suggestion
Asian black bear
Are you having trouble with this?

    const socialLinks = Object.keys(socialLinkItems).map((title, index) => {
        return (
            <Image src={socialLinkItems[title]} />
        )
    }
my suggestion was if you want to use the imported images and the url at the same time you can do:
    const socialLinkItems: { [key: string]: string } = {
        twitter: [twitter, "https://twitter.com"],
        // ...
    };
Lithuanian HoundOP
Ah, yah, that's what I thought you meant with the first comment and what I ended up doing 🙂