Search code examples
javascriptnode.jsreactjsnpmmaterialize

Can't import Materialize CSS JS react


Good morning everyone,

I've been struggling to get materialize css to work on my react-app, specifically, the Javascript files.

I've tried multiple ways, but this is the one I think i've gotten farther.

In my 'landingpage.js' file:

import React, { Component } from 'react';
import './styles/css/custom.css';
import $ from 'jquery';
import 'materialize-css'; // It installs the JS asset only
import '../node_modules/materialize-css/js/modal';

The objective is to open a simple popup (so I can test if the JS is being imported correctly)

            <div>
            <a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal</a>
            <div id="modal1" class="modal">
                <div class="modal-content">
                <h4>Modal Header</h4>
                <p>A bunch of text</p>
                </div>
                <div class="modal-footer">
                <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a>
                </div>
            </div>    
        </div>

So, as soon as the component mounts:

   componentDidMount() {
    $('.modal').modal();
}

When I click the button, it's supposed to open a popup, however:

ReferenceError: Component is not defined

This error occurs on the JS file i'm trying to import.

I tried importing in many different ways and the app would not even recognize anything. I've been trying to import this for two days and searched the web a lot, I'm doing this for a School Final project, trying to self learn react.

Here's the link to the framework i'm trying to import:

https://materializecss.com/modals.html#!

Thank you for your time.


Solution

  • You need to add your full path from npm module into your entry point file for webpack to utilize your css...

    here is an example in a typical create-react-app using Index.js or what ever your calling it if you are doing your own react boilerplate.

    Index.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import 'materialize-css/dist/css/materialize.min.css'; // <---
    
    import App from './components/App';
    
    ReactDOM.render(<App />, document.getElementById('root'));
    

    Once this is done your components will be able to have access to the css properties. I also recommend you install the npm i -S materialize-css@next so you can use JS components without needing JQuery