Search code examples
reactjsmaterialize

Initializing materialize in react apps


I am new to ReactJS. So I have a straight forward question.

I have used materialize cdn, included in index.html. But when I try to initialize it in my component it says 'M' not defined. Where should I initialize the same.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"
    />

    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
    <title>React App</title>
  </head>

  <body>
    <noscript> You need to enable JavaScript to run this app. </noscript>
    <div id="root"></div>
  </body>
</html>

My component looks something like this

import React from "react";

class Dashboard extends React.Component {
  componentDidMount() {
    document.addEventListener("DOMContentLoaded", function() {
      var elems = document.querySelectorAll(".carousel");
      var instances = M.Carousel.init(elems, options);
    });
  }
}

export default Dashboard;

CodeSandbox link: - https://codesandbox.io/s/40jvz6j590


Solution

  • Well, if you are using it, you need to import it :D

    import React from "react";
    import {Carousel} from "react-materialize";
    

    And here is how to use it https://react-materialize.github.io/#/carousel