Getting started with React Material UI

G
andrewgbliss
5 months ago

In this article we will install Material UI, talk about using styles in JavaScript, and some of the basic components Material UI has to give us.

. . .

Let's start out by installing Material UI

npm i @material-ui/core @material-ui/icons @material-ui/lab @material-ui/styles

This will install the core package along with icons, lab, and styles.

While that is installing, let's head on over to the Material UI website

https://material-ui.com/

Grid

So now that we have installed Material UI let's go over some basic components. Grid will help us align our components is a grid system. So let's see see how that works by aligning our text to the center of the screen.

import React, { useState } from 'react';
import Grid from '@material-ui/core/Grid';

const App = () => {
  return (
    <>
      <Grid container justify="center" alignItems="center">
        <Grid item>
          How to build a React app
        </Grid>
      </Grid>
    </>
  );
};

export default App;

This code doesn't fully center the text because the html document isn't a height of 100%. So what we can do is use a function called makeStyles.

makeStyles

Material UI gives us a way to create a styles hook, so that we use CSS classes in our component.

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
    height: '100%',
  }
}));

Now we can use this hook inside of our App component.

import React, { useState } from 'react';
import Grid from '@material-ui/core/Grid';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
    height: '100%',
  }
}));

const App = () => {
  const classes = useStyles();
  return (
    <>
      <Grid className={classes.root} container justify="center" alignItems="center">
        <Grid item>
          How to build a React app
        </Grid>
      </Grid>
    </>
  );
};

export default App;

Calling the useStyles function returns us a new classes object that we then can use in our className.

The results are still not showing the website with a height of 100%.

Let's create an index.css and add this CSS in that file.

html, body, div#root {
  width: 100%;
  height: 100%;
}

So now that we have created this file, let's include it in our app.

Inside the index.js file

import './index.css';

Paper

The Paper component will add a border and shadow to our component.

import Paper from '@material-ui/core/Paper';

<Paper elevation={8}>
  How to build a React app
</Paper>

Box

The Box component will enable us to easily add CSS without the need for classes.

import Box from '@material-ui/core/Box';

<Box p={2}>
  How to build a React app
</Box>

This will add 2 units of padding inside of our box.

Next Lesson

In the next lesson we will begin building out our Todo list application. We will go over more Material UI components and how to organize the app into folders.


G
andrewgbliss
5 months ago