How to use materialize-css with React?

后端 未结 13 1833
太阳男子
太阳男子 2020-12-07 17:52

I have a Meteor/React project, using ES6 modules. I\'ve installed materialize-css using npm, but I\'m not sure how to actually use the Materialize classes in my JSX code. Wh

13条回答
  •  旧时难觅i
    2020-12-07 18:06

    With NPM:

    Step 1) Install materialize

    npm install materialize-css@next 
    

    Check the materialize documentation for any updates. Don't miss the @next at the end. The installed version will be something like: ^1.0.0-rc.2 or ^1.0.0-alpha.4

    Step 2) Import materialize JS:

    import M from 'materialize-css'
    

    Or if that doesn't work you can try import M from 'materialize-css/dist/js/materialize.min.js'

    Step 3) Import materialize CSS:

    In index.html

    
    

    OR in javascript

    import 'materialize-css/dist/css/materialize.min.css'
    

    In order for the css import to work, you would need a css loader. Note that this loader is already included in projects built using create-react-app so you don't need the next steps. If instead, you are using custom webpack config, then run:

    npm install --save-dev style-loader css-loader
    

    Now add css-loader and style-loader in webpack config

    const path = require("path");
    
    module.exports = {
        entry: "./src/index.js",
        output: {
            filename: "bundle.js",
            path: path.join(__dirname, "build")
        },
        module: {
            rules: [
                {
                    test: /\.css$/,
                    use: [
                        'style-loader',
                        'css-loader'
                    ]
                },
                {
                    test: /.js$/,
                    exclude: /(node_modules)/,
                    use: {
                        loader: "babel-loader",
                        options: {
                            presets: ["env", "react"]
                        }
                    }
                }
            ]
        }
    }
    

    Now you can initialize components individually, or all at once using M.AutoInit();

    Step 4) Import materialize icons:

    
    

    With CDN:

    Add the following in your HTML file.

    
    
    
    
    
    
    
    
    

    Then, in the webpack config, add externals: https://webpack.js.org/configuration/externals/

提交回复
热议问题