How to use materialize-css with React?

72,311

Solution 1

Since I use CSS Modules, importing materialize css would scope it to that particular component. So I did the following

Step 1) install materialise

npm install materialize-css@next 

Step 2) in index.html

<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.3/css/materialize.min.css">

Step 3) import materialise.js in whichever component its needed

for e.g. in SomeComponent.js (for e.g. if this is about a sidenav)

import React from 'react';
import M from 'materialize-css';
....
// ref can only be used on class components
class SomeComponent extends Component {
  // get a reference to the element after the component has mounted
  componentDidMount(){
    M.Sidenav.init(this.sidenav);
  }

  render(){
    return (
      <ul className={this.props.classes}
          ref={ (sidenav) => {this.sidenav = sidenav} }
          id={this.props.id}>
        // menuItems
      </ul>
    )
  }
}

just a beginner, so I would appreciate any comments on downsides of this method

Solution 2

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

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

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:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

With CDN:

Add the following in your HTML file.

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

<!-- Materialize JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>

<!-- Materialize Icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

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

Solution 3

You can use https://react-materialize.github.io/#/, why to reinvent the wheel.

installation react-materialize

npm install react-materialize

Usage

import {Button, Icon} from 'react-materialize'

export default () => (
  <Button waves='light'>
    <Icon>thumb_up</Icon>
  </Button>
)

Sample

https://github.com/hiteshsahu/react-materializecss-template

Screenshot

enter image description here

Solution 4

There are several ways of using Materialize CSS in ReactJS. However, I always use the following easiest one.

Here you can use Materialize CSS classes just like your HTML site using only ClassName with tags.


1 ) Install Materialize CSS for ReactJS using NPM.

npm install materialize-css@next 

2 ) Then import the minified materialize CSS file to index.js file.

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

3 ) Now if you want to use google icons add the following codes in your public / index.html file.

<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

4 ) Finally to use Javascript events on input forms or other places add the following codes in your public / index.html file.

 <!-- Compiled and minified JavaScript -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

N.B. => Since all files need to go through the index.js file, so importing your minified Materialize CSS to index.js once is enough. Otherwise, you need to import these CSS files to all your js files.


That's enough to prepare your ReactJS folder for up and running with Materialize CSS. Happy Coding.


Solution 5

There are possible ways that I can recommend to use:

  1. One way is just include your stylesheet file in index.html and use className property in your React components just like this.

        var myDivElement = <div className="foo" />;
        ReactDOM.render(myDivElement, document.getElementById('example'));
    
  2. Another way is to bundle all your stylesheeets in one stylesheet file and to use them as previous one.

  3. One option could be to use webpack. By using webpack, it is possible to use embedded stylesheets in jsx files just by requiring stylesheet that you want to include.

    require("./stylesheet.css")

    To examine in detail webpack stylesheet option: http://webpack.github.io/docs/stylesheets.html

  4. Also see JedWatson's classnames repo for conditional className usage. https://github.com/JedWatson/classnames
Share:
72,311

Related videos on Youtube

ffxsam
Author by

ffxsam

Updated on May 10, 2021

Comments

  • ffxsam
    ffxsam almost 3 years

    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. What am I supposed to import from materialize-css? Or do I just have to include the CSS in my main index.html file?

    I mostly want it for the grid system, as I'll be using material-ui for the actual UI components.

  • Ryan Plant
    Ryan Plant almost 7 years
    React-Materialize only implements a subset of Materialize's components, so it's still desirable to find a way to use Materialize itself.
  • keaglin
    keaglin over 5 years
    Thanks! Using npm worked for me for initializing my Materialize'd <select> using React 16.6.0. Previously, using the CDN links alone didn't do it, no matter where I tried to add the code to initialize. Although I think using a separate, static JS file in the public/ dir worked, I never liked it as a long-term solution.
  • Hitesh Sahu
    Hitesh Sahu over 4 years
    I find Material-UI as alternative to Materilize CSS. It implement most materail ui components and have plenty of examples to jump start. I even made my web page using matetial-ui see HiteshSahu.com
  • Francisco Souza
    Francisco Souza over 4 years
    Where can I see all these icons? I don't see how to use them if I don't know what they are.
  • Kostanos
    Kostanos over 4 years
    Actually React-Materialize is re-inventing the staff. If you use this library, you'll see the final classes that actually div, nav and other elements, will have the particular names, and not the same names as the materialize CSS. Which by my opinion bring a lot of confusion, and extra staff to learn. I do prefer to import CSS as @supi suggested.
  • Rishav
    Rishav about 4 years
    Do I also need to add JQuery and Materialize.min.js or does the npm lib takes care of it?
  • supi
    supi about 4 years
    the npm lib takes care of it.
  • Rishav
    Rishav about 4 years
    Nice. Also JQuery is no longer a dependency for Materialize.
  • beeftosino
    beeftosino about 4 years
    I thought materialize-css and react-materialize were the same, but they are completely different. If you want to use the APIs in React Materialize Follow the instructions there. It is better than decoding all the answers here.
  • Aryamaan Goswamy
    Aryamaan Goswamy almost 4 years
    I made an <h3> tag and a <select> tag nested inside a <div> tag. My select tag isn't visible. Please help.
  • IFTEKHAR I ASIF
    IFTEKHAR I ASIF almost 4 years
    For icon, you can check any of the links below: material.io/resources/icons/?style=baseline materializecss.com/icons.html
  • harschware
    harschware over 3 years
    @HiteshSahu sample link is 404

Related