user15030566
user15030566

Reputation:

Not showing images in browser - React

I am trying to fetch the right image based on current state in my function, but for some reason everything works, just images are not available in browser and I have no idea why.

 const [firstImage, setFirstImage] = useState(1); //name of the image is 1.png

Returning an image - the path is of course correct:

<img src={`../assets/images/${firstImage}.png`}/>

Upvotes: 1

Views: 1654

Answers (1)

user14849955
user14849955

Reputation:

First you need to import your images, then add the images your state or an array of images. Then you can target or cycle through the images with your setImage index state value.

These links show why you cant just use pathnames:

https://create-react-app.dev/docs/adding-images-fonts-and-files/

https://www.edwardbeazer.com/importing-images-with-react/

https://daveceddia.com/react-image-tag/

Heres an example: https://codesandbox.io/s/competent-rgb-zxz36?file=/src/App.js:0-346

import React, { useState } from "react";
import "./styles.css";
// import img1 from "./img/img1.jpg"; // you can import them
// import img2 from "./img/img2.jpg";

export default function App() {
  const img1 = require(`./img/img1.jpg`); // or you can require them
  const img2 = require(`./img/img2.jpg`);
  const images = [img1, img2];
  const [currentImage, setCurrentImage] = useState(0);
  return (
    <div className="App">
      <img src={images[currentImage]} />
    </div>
  );
}

Upvotes: 1

Related Questions