header-banner-image

Hello, We Are

Codyssey

Let's make your

digital ideas a reality

Back to blog

6 January 2018

Material UI with React

Post By:

blog-image

What is Material Design ?

You might be hearing about material design frequently these days.What is material design? According to material.io:

Material Design is a unified system that combines theory, resources, and tools for crafting digital experiences.

Material Design is this concept developed by Google which makes the design of our application neat,clean and highly attractive.It contains various rules for animation, style, layout, components, patterns and usability.It is a visual language to help designers create websites and apps that are accessible,practical and usable.This concept of design has highly influenced designers with an awesome documentation found here.

Why Material Design ?

Material design provides designers a UI framework.To avoid making awful interfaces,material design shows a clear path regarding how to design animations,styles,layouts,components and patterns.

Advantages of material design

  • Unified simplistic approach
  • Principles and goals provide consistency for designers
  • Z-axis creates the depth
  • Intitutive to use
  • Uses motion to show users what is happening on screen

Components of Material UI

Material Design describes every element in detail.From how to create it,to where should the element be placed in the screen.Some of the common elements are:

  • Paper
  • Buttons
  • Cards
  • Dialogs
  • Dividers
  • Grids
  • Lists
  • Menus
  • Pickers
  • Progress bars
  • AppBar
  • Drawers
  • Snackbars
  • TextFields

Installation

Material Design can be integrated in various frameworks like React,Angular etc.This blog post mainly focuses on implementing Material-UI in a React application.Material-UI is a library that implements the google material design.To use Material-UI in an existing app,just install a npm package.

npm install --save material-ui@next

Importing components in our react application is easy:

import Grid from 'material-ui/Grid'
import Paper from 'material-ui/Paper'

Layouts and Design

There are lots of components as mentioned earlier,but this blog post features only a few important ones.

Grid

Material Design’s responsive UI is based on a 12-column grid layout.The grid layout creates visual consistency between layouts while allowing flexibility accross all designs.The concept of Grid in material-ui is similar to bootstrap’s grid.

  • There are two types of layout in Grid layout: containers and items.Items widths are set in percentages so they always fluid and sized according to their parent element.Items resides inside containers.
  • There are five grid breakpoints:
    Breakpoints dp
    xs(extra small) 0dp or larger
    sm(small) 600dp or larger
    md(medium) 960dp or larger
    lg(large) 1280dp or larger
    xl(extra-large) 1920dp or larger
 import React from 'material-ui/React'
 import Grid from 'material-ui/Grid'
 import Paper from 'material-ui/Paper'
 import Button from 'material-ui/Button'
 class GridExample extends Component {
   render(){
     return(
       <Grid container spacing={8}>
          <Grid item xs={12} sm={12} md={12} lg={12}>
              <Paper>
                <p>
                  Being entirely honest with oneself is a good exercise. Sigmund Freud.
                </p>
              </Paper>
          </Grid>
          <Grid item xs={6} sm={6} md={6} lg={12}>
            <Grid container spacing={8}>
              <Grid item xs={10} sm={10} md={10} lg={10}>
                <Paper>
                  <p>
                    But a man is not made for defeat. A man can be destroyed but not defeated.
                  </p>
                </Paper>
              </Grid>
              <Grid item xs={2} sm={2} md={2} lg={2}>
                  <Button>close me </Button>
              </Grid>
          </Grid>
       </Grid>
     )
   }
 }
 export default GridExample

Papers and Cards

Material design tries to translate the physical proporties of paper into the screen.Cards are generally taken as an entry point to something descriptive.Cards and Paper both can contain various elements whose size or actions can vary. A card may contain simple information,media,buttons(UI controls) etc. Using Paper and Cards is easy.

  import React,{Component} from 'react'
  import Paper from 'material-ui/Paper'
  import Card from 'material-ui/Card'
  import Typography from 'material-ui/Typography'

  class PaperCard extends Component{
    render(){
      return(
        <div>
          <Paper>
            <h1>Paper Example</h1>
            <Typography component="p">
              Paper alongside cards
            </Typography>
          </Paper>
          <Card>
            <CardContent>
              <Typography type="title">
                Word of the day
              </Typography>
              <Typography type="headline" component="h2">
                impediments
              </Typography>
              <Typography component="p">
                adjective
              </Typography>
            </CardContent>
            <CardActions>
              <Button dense> Learn More </Button>
            </CardActions>
          </Card>
        </div>
      )
    }
  }
export default PaperCard

The pyhysical proporties of paper are translated to the screen.The background of an application resembles the flat,opaque texture of a sheet of paper, and an application’s behaviour mimics paper’s ability to be re-sized,shuffle,and bound together multiple sheets.

Dialog

Dialog informs user about a specific task and contains other elements and controls.They inform users about critical information, require users to make decisions,or involve multiple tasks.A simple alert dialog example is as follows:

  import React from 'react';
  import Button from 'material-ui/Button';
  import Dialog, {
    DialogActions,
    DialogContent,
    DialogContentText,
    DialogTitle,
  } from 'material-ui/Dialog';
  class AlertDialog extends React.Component {
   contructor(props){
    state = {
      open: false,
    };
   }

   handleClickOpen = () => {
    this.setState({ open: true });
   };

   handleClose = () => {
    this.setState({ open: false });
   };

   render() {
       return (
          <div>
            <Button onClick={this.handleClickOpen}>Open alert dialog</Button>
            <Dialog
              open={this.state.open}
              onClose={this.handleClose}
            >
              <DialogTitle >Do you want to  enable cookies?</DialogTitle>
              <DialogContent>
                <DialogContentText>
                  Let us help improve the performance by enabling cookies?
                </DialogContentText>
              </DialogContent>
              <DialogActions>
                <Button onClick={this.handleClose} color="primary">
                  Disagree
                </Button>
                <Button onClick={this.handleClose} color="primary" autoFocus>
                  Agree
                </Button>
              </DialogActions>
            </Dialog>
          </div>
      );
    }
  }

export default AlertDialog;

TextFields

TextFields are the components for letting users input some value and usually appears in a form.Input fields may be of type text,numbers,dropdowns etc.

  import React from 'react'
  import TextField from 'material-ui/TextField'
  import Button from 'material-ui/Button'

  class App extends Component {
   render() {
    return (
      <form className='formStyle'>
        <TextField fullWidth type= 'text'
          placeholder= 'What did you work on yesterday?'/>
        <TextField fullWidth type= 'text'
          placeholder= 'What are you planning to work on today?'/>
        <TextField fullWidth type= 'text'
          placeholder= 'Any impediments in your way?'/>
        <Button raised color='primary' type='submit'>Submit</Button>
       </form>
      )
    }
  }

export default App;

Colors,Icons and Typography

Color in Material-UI is inspired by bold hues juxtaposed with muted environments, deep shadows, and bright highlights. The material.io provides a powerful color-tool to create,share,and apply color palettes to your UI, as well as measure the accessibility level of any color combination.A palette is the combination of primary and accent colors.

To import colors:

import {cyan, green} from 'material-ui/colors'
const primary = cyan[500]
const accent = green[600]

Material-UI provides a typographic scale, from which we can extract the ones that are useful to make the web application attractive. Typography is imported as:

 import Typography from 'material-ui/Typography'

Various proporties can be passed to Typography like as the following:

   <Typography type="headline" component="h3">
      Material Design
   </Typography>
   <Typography component="p">
      Material Design is killing the web.
   </Typography>
   <Typography type="caption" align="center">
      caption
   </Typography>

CSS to the Components

To provide users to write custom CSS to the components(Material-UI), Material-UI follows CSS-in-JS style. A CSS-in-JS looks like the following:

...
import {withStyles} from 'material-ui/styles'
const styles = theme => ({
  root: {
    color: 'red'
  },
})

First of all, we import withStyles from material-ui/styles. Then we define the styles method which returns an object containing our styles.To implement the stylesheet:-

class CssInJs extends Component {
  render(){
    const{ classes } = this.props
    return(
      <div className={classes.root}>
        <Typography component="p">
          Try not to become a man of success, but rather try to be a man of value.
        </Typography>
      </div>
    )
  }
}
export default withStyles(styles)(CssInJs)

PropTypes of the Components

PropTypes may vary from components to components.But proporties like classes and className is available in every components to customize the CSS.Any props can be passed to the components according to their API.React application nowadys,no longer report on incorrect props being passed to Components,it is important to pass valid propTypes.

We can pass propTypes like transition,open in the Dialog component whereas elevation,square to Paper.A textField can have error,defaultValue props and the list of props goes on and on.For more information about component proporties look at material-ui-next.

Other React Component libraries:

There are lots of alternatives out there to choose a material design based UI framework for react.Some of them are:

Back to blog