Skip to content
Advertisement

Fixing Uncaught TypeError: Cannot read properties of undefined (reading ‘style’)

I’m trying to make a slideshow in my react app. I’m using the below function for the slideshow.

var myIndex = 0;
carousel();

function carousel() {
  var i;
  var x = document.getElementsByClassName("diabetes-day");
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  myIndex++;
  if (myIndex > x.length) {
    myIndex = 1
  }
  x[myIndex - 1].style.display = "block";
  setTimeout(carousel, 5000); // Change image every 5 seconds
}
<div className="slideshow-container">
  <div className="diabetes-news">
    <img className="diabetes-day" src={DiabetesDay}/>
    <img className="diabetes-day" src={Symptoms}/>
    <img className="diabetes-day" src={Managing}/>
  </div>
</div>

When I run the code the slideshow works. But as soon as I refresh the page all the contents in the page disappears and I get the following error in my console.Screenshot of the Error

I’m not quite sure why it stops working once the page is refreshed. It would be great if someone could guide me on how to fix this.

Advertisement

Answer

it seems that you are working with reactjs, it’s better to change your code with this :

const {useState, useEffect} = React;

const Example = () => {
  const [imageIndex, setImageIndex] = useState(0);

  // change these images with yours
  const imagesSrc = [
    "https://cdn.pixabay.com/photo/2022/03/03/11/19/nature-7045133_960_720.jpg",
    "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_960_720.jpg",
    "https://cdn.pixabay.com/photo/2013/07/18/20/26/sea-164989_960_720.jpg",
  ];

  const carousel = () => {
    setImageIndex((prev) => (prev < 2 ? prev + 1 : 0));
  };

  useEffect(() => {
    const timer = setInterval(() => {
      carousel();
    }, 2000); // set the which timer you want
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div className="slideshow-container">
      <div className="diabetes-news">
        <img className="diabetes-day" src={imagesSrc[imageIndex]} alt="" />
      </div>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example/>,
  document.getElementById("react")
);
.diabetes-day{
  width: 200px;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement