Home > Enterprise >  Dynamic loading of images in React JS
Dynamic loading of images in React JS

Time:10-23

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>
    )
}

CodePudding user response:

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

CodePudding user response:

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 taken 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.

  • Related