3

I am trying to dynamically get images from my images folder based on some information retrieved from the database. Gone through as many resources as I could but still unable to solve the problem. Here's my code:

import scimitar from "../../images/scimitar.png";
import defender from "../../images/defender.png";
import arrows from "../../images/arrows.png";
import cape from "../../images/cape.png";
import platebody from "../../images/platebody.png";

const ItemCard = ({ item }) => {


    return (
        <div>
            <p key={item.id}>ID: {item.id}</p>
            <p>Name: {item.name}</p>
            <p>{item.examine}</p>
            <p>
                <Link to={`/items/${item.id}`}>{item.name}</Link>
            </p>

            <img src={require(item.name)} alt={item.examine} />
        </div>
    )
}

const ItemList = () => {
    const [items, setItems] = useState(null);

    const populateItems = async () => {
        const data = await getItems();
        setItems(data);
    };

    useEffect(() => populateItems(), []);


    return (
        <div>
            {items &&
                items.map((item, index) => (
                    <ItemCard item={item} key={index} />
                ))
            }
        </div>
    )
}
4
  • The value of src needs to be the path to your image as a string. You shouldn't use require in there. developer.mozilla.org/en-US/docs/Web/HTML/Element/img Commented Oct 23, 2021 at 2:52
  • I'd also try to console.log({data}) in populateItems to make sure getItems() is working properly. Commented Oct 23, 2021 at 2:53
  • @JosephCho Yup I was able to retrieve information back from the database, only field that was giving me trouble was the image unfortunately Commented Oct 23, 2021 at 4:16
  • @jmargolisvt so something like <img src={../../images/${item.name}.png} alt={item.examine} /> wouldn't work either? Commented Oct 23, 2021 at 4:21

4 Answers 4

4

It looks like there are a couple of issues going on. Using template literals like

<img src={`../../images/${item.name}.png`} alt={item.examine} />

won't work either. The reason why is src doesn't take in a path to picture, it looks at a url your website uses. You'll need to setup your React app to serve public images (e.g. make sure something like localhost:1337/images/schimitar.png works).

Only then can you reference it using

<img src={`/images/${item.name}.png` />

To serve static files in create-react-app check out this link. If you have another setup you'll need to use something like babel-plugin-file-loader to serve public assets.

Sign up to request clarification or add additional context in comments.

2 Comments

I was actually able to retrieve the image dynamically by placing the path of the image in a variable then inserting that variable into the src path of the image. const imageItem = /images/${item.name}.png; <img src={imageItem} alt={item.examine} />
@JeremyChee nice job. Don't forget the reason it works is because you're already serving public files (e.g. /images/schimitar.png). Later on with different frameworks and codebases it'll be important to know. For example Next.js has a built in /public directory, but in Angular it's /dist.
0

Not sure why this worked but I placed the path of the image in a variable before passing it to the src path of the image tag.

const ItemCard = ({ item }) => {
const imageItem = `/images/${item.name}.png`;

return (
    <div>
        <p key={item.id}>ID: {item.id}</p>
        <p>Name: {item.name}</p>
        <p>{item.examine}</p>
        <span>Quantity: {item.quantity}</span>
        <p>
            <Link to={`/items/${item.id}`}>{item.name}</Link>
        </p>
        <img src={imageItem} alt={item.examine} />

    </div>
  )
}
export default ItemCard;

Comments

0
<img src={item.name} alt={item.examine} />

1 Comment

a side note just for improvement: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂
-1

Try the following code if you are trying to get the image from a static path.

import image1 from 'images/image1.png';

<img src={image1} alt="image1" />

If you are trying to dynamically add the image then try the following code,

const imgName = "image1.png"

return (
    <div>
         { imgName && <img src={`images/${imgName}`} alt="imgName" /> }
    </div>
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.