2

I am using MaterializeCSS in react application. On using Carousel in my render with javascript code for it. I get error at M

 class App extends React.Component {

   render() {
       document.addEventListener('DOMContentLoaded', function() {
       var elems = document.querySelectorAll('.carousel');
       var instances = M.Carousel.init(elems, options);
  });
        return (
          <div>
     <div class="carousel">
        <a class="carousel-item" href="#one!"><img src="https://lorempixel.com/250/250/nature/1"></a>
        <a class="carousel-item" href="#two!"><img src="https://lorempixel.com/250/250/nature/2"></a>
        <a class="carousel-item" href="#three!"><img src="https://lorempixel.com/250/250/nature/3"></a>
        <a class="carousel-item" href="#four!"><img src="https://lorempixel.com/250/250/nature/4"></a>
        <a class="carousel-item" href="#five!"><img src="https://lorempixel.com/250/250/nature/5"></a>
      </div>
         </div>
        )
      }
    }
Abhishek Konnur
  • 503
  • 1
  • 9
  • 33

1 Answers1

0

You should initialize Carousel in componentDidMount() event of React Lifecycle to make sure if DOM has been loaded fully.

use it and let render() be neat and clean.

componentDidMount(){
   document.addEventListener('DOMContentLoaded', function() {
       var elems = document.querySelectorAll('.carousel');
       var instances = M.Carousel.init(elems, options);
  });
}

Also I assume you've options defined in the Component.

Manoz
  • 6,507
  • 13
  • 68
  • 114