Home > Enterprise >  How to render an image every 5 seconds in React?
How to render an image every 5 seconds in React?

Time:10-19

Every time you enter this url: https://picsum.photos/200, is shown a different image. I want my react component to render every 5 seconds a different image with this url, but I can't do it. This is my code:

import { useEffect, useState } from "react";

const VariableImage = () => {
  const imageUrl = "https://picsum.photos/200";

  const [image, setImage] = useState(imageUrl);

  useEffect(() => {
    setInterval(() => {
      const newImage = new Image();
      newImage.src = imageUrl;
      setImage(imageUrl);
    }, 5000);
  }, [imageUrl]);

  return (
    <>
      <img src={image} alt="scenery" height="200" width="200" />
    </>
  );
};

export default VariableImage;

An image is shown in first render but later don't change. If anyone could help me I would be very grateful. Thanks.

CodePudding user response:

Add a dummy randomized query parameter to the external URL so as to force the browser to make a new request (and give you a new image).

Doing new Image isn't helping you any here - you can leave that off entirely.

const { useEffect, useState } = React;

const imageUrl = "https://picsum.photos/200";
const VariableImage = () => {
  const [src, setSrc] = useState(imageUrl);
  useEffect(() => {
    setInterval(() => {
      setSrc(imageUrl   '?forcerefresh='   Math.random());
    }, 5000);
  }, []);

  return <img src={src} alt="scenery" height="200" width="200" />;
};

ReactDOM.createRoot(document.querySelector('.react')).render(<VariableImage />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='react'></div>

CodePudding user response:

' You are adding the same imageUrl(reference) into it, because of which react is not able to find any changes so it is not updating the state. '

Example with vanilla js.

const img = document.querySelector("img");

setInterval(() => {
  img.src = "https://picsum.photos/200"   "?forcerefresh="   Math.random();
}, 5000);
<image src="https://picsum.photos/200" />

Please add clearInterval(id) to stop the time when the component unmounts.

const { useEffect, useState } = React;

const imageUrl = "https://picsum.photos/200";
const VariableImage = () => {
  const [src, setSrc] = useState(imageUrl);
  useEffect(() => {
    const id = setInterval(() => {
      setSrc(imageUrl   "?forcerefresh="   Math.random());
    }, 5000);

    return () => clearInterval(id)
  }, []);

  return (
   <>
     <img src={src} alt="scenery" height="200" width="200" />
   </>
  )

};

  • Related