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>
        )
      }
    }
6
  • Which error? Can you share the traceback? How do you import "M"?
    – keul
    Jul 20, 2018 at 9:31
  • I used this directly from materializeCSS documentation Jul 20, 2018 at 10:11
  • M is undefined i got Jul 20, 2018 at 10:11
  • OK, so you need to import 'M' from somewhere. I've no idea of what documentation you are talking about, can you share it also?
    – keul
    Jul 20, 2018 at 10:30

1 Answer 1

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.

1
  • In this case, you'll get erros, M is undefined and then init is undefined. Jul 22, 2018 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.