简体   繁体   中英

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.

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

using jquery with react is not recommended at all if you trying to use material how about using a library like

material-ui install it by using

npm i material-ui --save 

and you can follow the example here for dialog which is basically a modal dialog in material ui

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM