Getting started with Material Design Components for web
Note: This article is a few years old, so it may be worth visiting https://material.io/develop/web to get the latest tutorials on implementation.
Material Design Components for the web (MDC Web) offers designers and developers a way to implement Material Design in their websites. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional web projects.
MDC web is the successor to Material Design Lite, and in this article we are going to go through a basic set up of how to use MDC web.
There are two ways to include MDC Web: either by adding a few lines of code and instantiating the JavaScript file or by using MDC Web as Node modules, bundling the Sass and JavaScript yourself using something like webpack.
Let’s first take a look at the simple way of adding the MDC Web.
Quick start
First, let’s create a blank HTML
page, and create a simple button.
<button class=”foo-button mdc-button”>Button</button>
It has a custom CSS class of .foo-button
This class is what we will use to instantiate the JavaScript and give the button the Material Design ripple effect when a user presses or taps the button.
Nothing is happening yet because we haven’t added the master CSS
file. You can use a link to our CDN by adding a <link>
to the head of your HTML
doc:
<link rel=”stylesheet” href=”https://unpkg.com/material-components-web/dist/material-components-web.min.css">
The button should be styled now, but will need the JS file to enable the ripple effects. To do that we now need to add the JS
file to the HTML
doc:
<script src=”https://unpkg.com/material-components-web/dist/material-components-web.min.js"></script>
The final piece of the puzzle is to instantiate the button. As we gave it a custom CSS
class, we will reference that in the call. Create a JS
file or add this to your HTML
doc:
const button = document.querySelector(‘.foo-button’);mdc.ripple.MDCRipple.attachTo(button);
To view a working example head over to Codepen. We also have many more working components that you can see at our web catalogue. But for now let’s customise our button a little but using the Material Design icon set. First we will need to include the icon font:
<link rel=”stylesheet” href=”https://fonts.googleapis.com/icon?family=Material+Icons">
Next let’s add a new button with a favorite icon:
<button class=”bar-button mdc-button”><i class=”material-icons mdc-button__icon” aria-hidden=”true”>favorite</i>
Favorite
</button>
If we want to add a ripple to this button as well we will need to instantiate it like before;
const secondButton = document.querySelector(‘.bar-button’);mdc.ripple.MDCRipple.attachTo(secondButton);
We could also edit some of the button styles by adding different class styles to them. We have six different styling options, the default being a flat button. There is also raised, unelevated, outlined, icon. and dense. You can see more documentation on buttons here.
The code above can get quite repetitive as we add more and more buttons. So we can refactor in one of two ways: either by creating an array then running a forEach
loop or by using a utility called auto-init.
Foreach [Codepen]
const buttons = document.querySelectorAll(‘.mdc-button’);for (const button of buttons) { mdc.ripple.MDCRipple.attachTo(button);}
Auto init [Codepen]
If you are making a basic static site auto-init is a great utility to use. You do lose control of individual elements, so it is only really recommend for simple sites. You need to add a data-*
attribute and then call autoInit once in the JS
file:
<button class=”mdc-button mdc-button — outlined” data-mdc-auto-init=”MDCRipple”> Outline</button>
Then in the JS
we add:
mdc.autoInit();
Using SASS
To set up you will need Node.js and npm installed locally. Once you have these installed, run this command in your Terminal app or equivalent:
npm init
This sets up your package.json
file for dependencies. The command-line interface will ask you to fill out each section, such as the name and version of your project. Alternatively, simply copy and edit the below into your package.json file. The key is to add a start property to the scripts section:
{“name”: “PROJECTNAME”,“main”: “package.js”,“scripts”: { “start”: “webpack-dev-server”},}
Now we need to add all of the dependencies. You can run this command to add them automatically to your package file:
Note: We recommend using webpack 3, because we’re still investigating using webpack 4. We also recommend you use webpack-dev-server 2, because this works with webpack 3.
npm install --save-dev webpack@3 webpack-dev-server@2 css-loader sass-loader node-sass extract-loader file-loader
This installs the following dependencies:
- webpack: Bundles SASS and JavaScript
- webpack-dev-server: Development server
- sass-loader: Loads a Sass file and compiles it to CSS
- node-sass: Provides binding for Node.js to Sass, peer dependency to sass-loader
- css-loader: Resolves CSS @import and url() paths
- extract-loader: Extracts the CSS into a .css file
- file-loader: Serves the .css file as a public URL
In order to demonstrate how webpack bundles our SASS
, you’ll need an index.html
. This HTML
file needs to include CSS
. The CSS
is generated by sass-loader, which compiles Sass files into CSS
. The CSS
is extracted into a .css file by extract-loader. Create this simple “hello world” index.html
:
<!DOCTYPE html><html><head><title>Test project</title><link rel=”stylesheet” href=”bundle.css”></head><body>Hello World</body></html>
And create a simple Sass file called app.scss
:
body {color: red;}
Then configure webpack to convert app.scss
into bundle.css
. For that you need a new webpack.config.js
file : [Codepen can be seen here]
module.exports = [{entry: ‘./app.scss’,output: {// This is necessary for webpack to compile,// but we never use style-bundle.js.filename: ‘style-bundle.js’,},module: {rules: [{test: /\.scss$/,use: [{loader: ‘file-loader’,options: {name: ‘bundle.css’,},},{ loader: ‘extract-loader’ },{ loader: ‘css-loader’ },{ loader: ‘sass-loader’ },]}]},}];
To test your webpack configuration, run:
npm start
And open http://localhost:8080/ in a browser. You should see a red “Hello World”. If you make a change to the CSS
file, say turning the body color from red to blue, then refresh the browser the changes should happen instantly.
Adding components
If your server is still running, stop it for the time being. Now that we are all set up, let’s add some material components. First we will need to install the dependencies in the command line;
npm install --save-dev @material/button
We need to tell our app.scss
to import the SASS
files for @material/button. We can also use Sass mixins to customize the button. Replace your “hello world” version of app.scss
with this code:
@import “@material/button/mdc-button”;.foo-button {@include mdc-button-ink-color(teal);@include mdc-states(teal);}
We also need to configure sass-loader to understand the @material imports used by MDC Web. Update your webpack.config.js
by changing { loader: ‘sass-loader’ }
to:
{loader: ‘sass-loader’,options: {includePaths: [‘./node_modules’]}}
In order to add vendor-specific styles to the SASS
files, we need to configure autoprefixer through PostCSS.
You’ll need all of these Node dependencies:
- autoprefixer: Parses
CSS
and adds vendor prefixes toCSS
rules - postcss-loader: Loader for Webpack used in conjunction with autoprefixer
You can install all of them by running this command:
npm install --save-dev autoprefixer postcss-loader
Add autoprefixer at the top of your webpack.config.js
:
const autoprefixer = require(‘autoprefixer’);
Then add postcss-loader, using autoprefixer as a plugin [Codepen can be seen here]:
{ loader: ‘extract-loader’ },{ loader: ‘css-loader’ },{ loader: ‘postcss-loader’,options: {plugins: () => [autoprefixer()]}},
Now we can include the markup we used for the static HTML
file from the beginning. Update your index.html
to include the MDC Button markup, and add the foo-button class to the element:
<button class=”mdc-button foo-button”> Favorite</button>
Now run npm start again and open http://localhost:8080/. You should see a Material Design button! You can learn more about adding the relevant JS from the full getting started documentation site, but for now this should get you started with building MDC web components.
Special thanks to the MDC team, Lynn Jepson, Patty Rodee, Will Ernest, Mathias Bynens, Jason Miller and Jeffrey Posnick.