Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot import materialize-css in React project to use Chips

I have created project by command:

create-react-app app

I am using materialize-css http://materializecss.com/ and want to use Chips http://materializecss.com/chips.html.

import React, { Component } from 'react';
import $ from 'jquery';
import 'materialize-css';

class Form extends Component {
    constructor(props) {
        super(props);
        $(document).ready(function() {
            $('.chips').material_chip({
                data: [{
                   tag: 'Apple',
                }, {
                   tag: 'Microsoft',
                }, {
                   tag: 'Google',
                }],
            });
        });
    }
    render() {
        return (
            <div>
                <div className="chips"></div>
                <button>Add</button>
            </div>
        )
    }
}

I have tried to import:

import 'materialize-css/bin/materialize.css'
import 'materialize-css/bin/materialize.js'

But it's not working. The browser throw error:

Uncaught TypeError: $(...).material_chip is not a function
like image 654
Hoang Kien Avatar asked Jan 15 '17 04:01

Hoang Kien


People also ask

How do you install Materialise?

Step1: Go to http://materializecss.com/getting-started.html to download the latest version available. Step2: Put the downloaded materialize. min. js file in a directory of your website, e.g. /js and materialize.

What are the two ways to use materialize CSS?

There are two ways to use MaterializeCSS, either you can download the files on your system or use the files from CDN (Content Delivery Network).


Video Answer


2 Answers

Try this in your entry JS file

import 'materialize-css'; // It installs the JS asset only
import 'materialize-css/dist/css/materialize.min.css';

and you are done!


Update: I have put all the necessary details to get your code working. Try this out

index.jsx file is here

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import 'materialize-css';
import 'materialize-css/dist/css/materialize.min.css';

class Form extends Component {
  constructor(props) {
    super(props);
    $(document).ready(function() {
      $('.chips').material_chip({
        data: [{
          tag: 'Apple',
        }, {
          tag: 'Microsoft',
        }, {
          tag: 'Google',
        }],
      });
    });
  }
  render() {
    return (
        <div>
          <div className="chips"></div>
          <button>Add</button>
        </div>
    )
  }
}
ReactDOM.render(<Form />, document.getElementById('app'));

and package.json is like

"dependencies": {
    "babel-preset-react": "^6.16.0",
    "css-loader": "^0.26.1",
    "font-loader": "^0.1.2",
    "jquery": "^3.1.1",
    "materialize-css": "^0.97.8",
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "redux": "3.6.0",
    "style-loader": "^0.13.1"
  },
  "devDependencies": {
    "babel": "^6.5.2",
    "babel-core": "^6.21.0",
    "babel-loader": "^6.2.10",
    "babel-preset-es2015": "^6.18.0",
    "webpack": "^1.14.0",
    "webpack-dev-server": "^1.16.2",
    "webpack-hot-middleware": "^2.15.0"
  }

and webpack.config.js is

const webpack = require('webpack');

module.exports = {

  entry: [Screenshot from 2017-01-15 18-11-16
    "./src/index.jsx",
    "webpack-dev-server/client?http://localhost:3000/",
    "webpack/hot/only-dev-server"
  ],

  output: {
    filename: "bundle.js",
    path: __dirname + '/public'
  },
  devServer: {
    contentBase: './public',
    port: 3000
  },

  // Bundle lookup dir for included/imported modules
  // By default, bundler/webpack with search here for the scripts
  resolve: {
    modulesDirectories: ['node_modules', 'src'],
    extensions: ['', '.js', '.jsx']
  },


  // make sure you added babel-loader to the package
  // npm i babel-loader babel-core babel-preset-es2015 -D
  module: {
    loaders: [
      {
        test: /\.js[x]?$/, // Allowing .jsx file to be transpiled by babel
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react']
        }
      },
      { test: /\.css$/, loaders: [
        'style',
        'css?importLoaders=1',
        'font?format[]=truetype&format[]=woff&format[]=embedded-opentype'
      ] },
      { test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
        loader: 'file-loader?name=fonts/[name].[ext]' }
    ]
  },

  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ]

};

enter image description here No error whatsoever.

like image 191
illusionist Avatar answered Nov 09 '22 08:11

illusionist


With NPM:

Step 1: Install materialize

If you are using npm, make sure you install materialize using the command listed in their documentation:

npm install materialize-css@next 

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:

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

import M from 'materialize-css/dist/js/materialize.min.js'

OR

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

import M from 'materialize-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();


With CDN:

Add the following in your HTML file.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>

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

like image 41
Coding Elements Avatar answered Nov 09 '22 08:11

Coding Elements