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"? Commented Jul 20, 2018 at 9:31
  • I used this directly from materializeCSS documentation Commented Jul 20, 2018 at 10:11
  • M is undefined i got Commented 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? Commented Jul 20, 2018 at 10:30
  • materializecss.com/carousel.html Commented Jul 20, 2018 at 10:54

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In this case, you'll get erros, M is undefined and then init is undefined.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.