Material Design, react.js, UI, UX

React.js and Material Design Lite

I’m a bit of a React.js fan lately, and with the arrival of Google’s Material Design Lite, I decided to combine them for a little project I’m throwing together.  Turns out to be pretty easy.  To simplify the Getting Started, you need to include a .css and .js file in your page:

<link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.0/material.grey-blue.min.css" />
<script src="https://storage.googleapis.com/code.getmdl.io/1.0.0/material.min.js"></script>

…and then show a Material Design button using the following class names:

<button class="mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect">
  Button
</button>

The small gotcha for using templating techniques for dynamic pages such as with React.js is that for buttons, and other items, dynamically added you need to call a bit of script to upgrade the button:

//where button is your DOM element
componentHandler.upgradeElement(button, 'MaterialButton');

But when we come to create our React class, that’s easily handled in componentDidMount, leaving my Material Design Lite button class looking like this:

var MdlButton = React.createClass({
	handleClick: function() {
		this.props.onClick();	
	},
	render: function() {
		return (
			<button ref="btn" className="mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect"
					onClick={this.handleClick}>
				{this.props.content}
			</button>
		);
	},
	componentDidMount: function() {
		componentHandler.upgradeElement(React.findDOMNode(this.refs.btn), 'MaterialButton');		
	} 
});

One small thing to note is the second arg to upgradeElement where we are passing in ‘MaterialButton’. As of now the docs aren’t overly clear on this, but it’s the name of the Javascript function object defined in the source. So, if we want to create a check box React class we can dig in to the Material Design Light source code in GitHub, and confirm that we’d pass ‘MaterialCheckbox’ into upgradeElement.

No doubt the community will provide a full library for this in time, but it doesn’t take much to combine these two libraries.

Advertisements

One thought on “React.js and Material Design Lite

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s