Material UI Guide with Examples

Material UI Guide with Examples
Spread the love

The list of renowned React UI frameworks can’t be complete without Material UI’s name. In fact, it often tops the list due to its tremendous performance. You most likely know that, and that is the reason why you have landed here. Are you planning to use this advanced UI framework but don’t know how to get started? If nodding, this Material UI guide with examples will play the trick.

It leaves no stone unturned regarding this framework, including how to install and use it. Such information will help you create user interfaces using one of the most efficient tools. You also save a lot of time and effort creating interfacing and adding features. So, let’s discuss a detailed Material UI with examples.

What is Material UI?

Material UI, also known as Material Design for React, is a design language ideal for creating mobile and web-based applications. Google developed it in 2014; its inspiration is from the real world, including its textures. An excellent example of that inspiration is its realism in casting shadows and reflecting light. Equally important, its surfaces are similar to the paper and ink mediums.

Besides depth effects, it has other visual aspects such as padding, responsive transitions, responsive animations, and grid layouts. Developers use Material UI to ensure that creating a web-based or mobile application is as easy as it can get.

Benefits of Using Material UI

As much as there are other UI frameworks out there, there are reasons why most developers choose them. They include;

  • Its use of visual language characterized by lightning & shadows effects, grid system, design, and animations
  • It is also compatible with all JavaScript frameworks, including VueJS and AngularJS
  • It is also compatible with libraries such as ReactJS
  • The UI uses style functions which are low-level utility functions capable of building incredible designs for various systems and applications
  • It allows direct access to its theme values through component props
  • Its execution is also fast
  • Since it is gzipped, its file is also small, as it is less than a kilobyte (kb)
  • It is compatible with all theme objects
  • It is easy for developers to achieve responsiveness when using Material Design
  • Another thing it simplifies is the maintenance of consistency across the various components of your user interface

What Are The Goals of Material UI?

Material Design, or UI, has three goals, and they are as follows;

  • Create: Material UI isn’t just creating an application but also ensuring that this app lives up to the standards of a good design. It provides the developers with the visual language they need to achieve it.
  • Unify: The UI is a perfect underlying system for any web-based or mobile application. Regardless of what one designs, there is uniformity in the user experience irrespective of input methods, devices, and platforms, to mention a few.
  • Customization: Any developer and use it and then customize it to meet the requirements of their specific projects thanks to its flexibility. Besides, it enhances brand expression and innovation using visual language.

If you have such goals, let’s look at this Material UI guide with examples to help you get started.

What You Need To Get Started With Material UI

There are several prerequisites, including the following;

  • You should have the technical know-how to create a React application
  • Install a code editor such as Sublime, Atom, or VS Code, among other code editors available out there
  • Install NodeJS

Once you do so, it will be easy to follow this Material UI guide with examples to the end. Let’s dive in

React.js Installation

It is as simple as opening your terminal and running the following code in the directory you are working with.

npx create-react-app materialui

cd materialui

npm start

Some developers may find compiling this code a challenge. If it happens to you, don’t panic; instead, create a .env file. Ensure that it is on the root before adding this code.

SKIP_PREFLIGHT_CHECK=true

Material Design/Material UI Installation

It is as simple as running one of these commands

  1. npm install @material-ui/core –save
  2. yarn add @material-ui/core

Gain access to the Contentful backend by installing its respective JavaScript library, Contentful

$ npm install contentful

Last but not least, ensure that everything is okay by running this code;

$ npm start

If it is fine, it opens a browser and showcases the default React app’s start page. If so, proceed with the next step of our Material UI Guide with Examples.

There are various ways of using Material UI, including the following;

  1. Tables in Material UI Guide with Examples

If you want to display your data in a table, Material Design works excellently. Its features include a header row, columns and rows.

import Typography from “@mui/material/Typography”;

import Table from “@mui/material/Table”;

import TableBody from “@mui/material/TableBody”;

import TableCell from “@mui/material/TableCell”;

import TableHead from “@mui/material/TableHead”;

import TableRow from “@mui/material/TableRow”;

import TableContainer from “@mui/material/TableContainer”;

 

return (

<div>

<Typography variant=”h4″> List of Sessions:</Typography>

{/* First, create a container. */}

<TableContainer>

<Table>

{/* Now a Table head. (thead) */}

<TableHead>

{/*create row */}

<TableRow>

{/* create cells */}

<TableCell>Session</TableCell>

<TableCell>Students</TableCell>

</TableRow>

</TableHead>

{/* next, create body (tbody) */}

<TableBody>

<TableRow>

<TableCell>Biology </TableCell>

<TableCell> 200</TableCell>

</TableRow>

<TableRow>

<TableCell> Chemistry </TableCell>

<TableCell>200 </TableCell>

</TableRow>

 

</TableBody>

</Table>

</TableContainer>

</div>

);

 

Typography in Material MUI

The default font choice in Material UI is usually Roboto, but it isn’t part of the framework by default. Therefore, developers have to import it into their React apps. They can do so using either of the two approaches

Using npm

Type the command below in your terminal

npm install @fontsource/roboto

Don’t forget to import the font into your project as follows

import ‘@fontsource/roboto/300.css’;

import ‘@fontsource/roboto/400.css’;

import ‘@fontsource/roboto/500.css’;

import ‘@fontsource/roboto/700.css’;

If you want to display text in your application, don’t forget the Typography component

import Typography from “@mui/material/Typography”;

//now import CSS files:

import “@fontsource/roboto/300.css”;

import “@fontsource/roboto/400.css”;

import “@fontsource/roboto/500.css”;

import “@fontsource/roboto/700.css”;

 

export default function App() {

return (

<div className=”App”>

{/* create h1(title) */}

<Typography variant=”h1″>Use your phone for longer </Typography>

{/* create overline */}

<Typography variant=”overline”>Or buy a new one</Typography>

</div>

);

}

 

CSS Baseline

CssBaseline is equivalent to the normalize.css in HTML. It is responsible for the elegance, consistency and simplicity of the baseline you build your app. Its roles include;

  • Enables font initialization to display Roboto font perfectly
  • Applies the default background colour of Material UI
  • Removes margins across all browsers
  • Sets the default font size to 16px

You should import the baseline as follows;

import CssBaseline from “@mui/material/CssBaseline”;

return (

<div>

<CssBaseline /> {/* apply normalize.css */}

{/* Application code.. */}

</div>

);

Icons

Icons convey information and action, usually in lists, buttons, toolbars and app bars. They show actions such as save, print and trash. If you want to render font icons, use the Icon method. However, use the SvgIcon method to render SVG paths

import FavoriteIcon from “@mui/icons-material/Favorite”;

import FavoriteBorderOutlinedIcon from “@mui/icons-material/FavoriteBorderOutlined”;

return (

<div>

<FavoriteIcon style={{ width: “100%”, height: “20px” }} />

<FavoriteBorderOutlinedIcon style={{ width: “100%”, height: “20px” }} />

</div>

);

Grid Layout

In Material UI, the grid layout has 12 columns and helps developers maintain consistent visuals throughout the layers. Its feature include;

  • The grid layout uses Flexbox
  • Its items are fluid, whereas their sizes are relative to their respective parent elements since their widths are a percentage of that
  • Expect 5 grid breakpoints: xl, lg, md, sm and xs
  • It has 2 types of grid layouts; items and containers
  • Its padding aspects create space between items

The component is usually Grid, and here is an example.

import Grid from “@mui/material/Grid”;

//first, create a custom component. It will return a div element with a chosen colour.

function ColoredComponent({ color }) {

return (

<div

style={{

backgroundColor: color,

width: “100%”,

paddingTop: “20px”,

textAlign: “center”,

}}

>

<Typography variant=”overline”> Sample piece of text</Typography>

</div>

);

}

export default function App() {

return (

<div className=”App”>

{/* Each item will have 1 unit of spacing. The container prop will assign this component as a container*/}

<Grid container spacing={1}>

{/* on small screens(phones), this item takes up 5 units. On medium-sized screens(tablets), take up 8 units. If an item is too large, it will go to the next line. */}

<Grid item xs={5} md={8}>

<ColoredComponent color=”red” />

</Grid>

<Grid item xs={5} md={6}>

<ColoredComponent color=”blue” />

</Grid>

</Grid>

</div>

);

Buttons

A button is an interface that users use when making choices and taking action by tapping once. A developer will have to import this component button as follows.

import Button from ‘@mui/material/Button’;

 

<Button color=”success” variant=”contained”>

Welcome

</Button>

The component takes various props, including size, colour and variant. There are two forms of buttons;

  • Flat Buttons: These buttons have text and lack borders and background colour. However, you will notice the colour change upon clicking them. They are often used in toolbars, dialogues or inline.
  • Outlined Buttons: Unlike their flat counterparts, these buttons have an outline, although they also contain text only. If you hover over the button, you will see its background colour and border.

Material UI Components

If you are developing a React app and plan to build a material design theme, the following MUI components can help.

Navigation

A navigation menu usually has between 3 and 5 actions, and every action has a label and an icon. Here’s an example

import { useState } from “react”;

import BottomNavigation from “@mui/material/BottomNavigation”;

import BottomNavigationAction from “@mui/material/BottomNavigationAction”;

import RestoreIcon from “@mui/icons-material/Restore”;

import FavoriteIcon from “@mui/icons-material/Favorite”;

import LocationOnIcon from “@mui/icons-material/LocationOn”;

 

const [value, setValue] = useState(0);

 

return (

<div>

{ /* create the bar */ }

<BottomNavigation

showLabels

value={value}

onChange={(event, newValue) => {

setValue(newValue); //or change current view

}}

>

<BottomNavigationAction label=”Recents” icon={<RestoreIcon />} /> { /*Create an action button with an iconĀ  */}

<BottomNavigationAction label=”Favorites” icon={<FavoriteIcon />} />

<BottomNavigationAction label=”Nearby” icon={<LocationOnIcon />} />

</BottomNavigation>

<p> Value:{value}</p> {/* displays the current user selection index */ }

</div>

);

App Bar

Android used to refer to the App Bar as an action bar. It is a toolbar that serves as the header navigation menu used for actions, search, branding and navigation. This code will create one.

import AppBar from “@mui/material/AppBar”;

import Toolbar from “@mui/material/Toolbar”;

import Typography from “@mui/material/Typography”;

import HomeIcon from “@mui/icons-material/Home”;

 

<div>

<AppBar position=”static”>

<Toolbar> {/* Display a Toolbar at the top */}

<Typography>

Current page: <HomeIcon />

</Typography>

</Toolbar>

</AppBar>

</div>;

Lists

This component showcases items in multiple vertical lines. The result is a typical list.

import List from “@mui/material/List”;

import ListItem from “@mui/material/ListItem”;

import Typography from “@mui/material/Typography”;

 

return (

<div>

<Typography variant=”h4″> Groceries:</Typography>

<List>

<ListItem> Eggs</ListItem>

<ListItem> Fish</ListItem>

<ListItem> Milk</ListItem>

</List>

</div>

);

Tabs

If users have to view several views, the tabs can help them shift from one to another seamlessly.

import Typography from “@mui/material/Typography”;

function TabPanel(props) {

const { children, value, index } = props;

//if ‘value'(current user selection) and ‘index'(the corresponding index of the tab) is equal, then display the component

return (

<div>

{value === index && (

<div>

<Typography>{children}</Typography>

</div>

)}

</div>

);

}

The following code will render the tabs

import Tabs from “@mui/material/Tabs”;

import Tab from “@mui/material/Tab”;

import { useState } from “react”;

export default function App() {

const [value, setValue] = useState(0);

const handleChange = (event, newValue) => {

setValue(newValue);

};

 

return (

<div>

<div>

<Tabs

value={value}

onChange={handleChange} //the handleChange method will run when the user clicks on a tab

>

<Tab label=”Item One” /> {/* Create our tabs */}

<Tab label=”Item Two” />

</Tabs>

</div>

<TabPanel value={value} index={0}>

Item One

</TabPanel>

<TabPanel value={value} index={1}>

Item Two

</TabPanel>

<Typography>Value: {value} </Typography>

</div>

);

}

Cards

A card can serve as the entry point if you have content comprising several elements.

import Typography from “@mui/material/Typography”;

import CardContent from “@mui/material/CardContent”;

import CardActions from “@mui/material/CardActions”;

import Card from “@mui/material/Card”;

 

return (

<div>

<Card>

{/* define the main content of the card */}

<CardContent>

<Typography variant=”h2″> General Merchants</Typography>

<Typography variant=”overline”>

Buy Everything You Need Today

</Typography>

</CardContent>

{/* interact with the card here */}

<CardActions>

<Typography>

Shop With Us

</Typography>

</CardActions>

</Card>

</div>

);

Image List

It is not much different from the typical list other than the fact that the items are images. The component, in this case, is ImageList.

import Typography from “@mui/material/Typography”;

import ImageList from “@mui/material/ImageList”;

import ImageListItem from “@mui/material/ImageListItem”;

//first, define our data source.

const images = [

{

src: “photo url”,

alt: “black rose”,

},

{

src: “photo url”,

alt: “white rose”,

},

{

src: “photo url”,

alt: “red rose”,

},

];

return (

<div>

<Typography variant=”h4″> My images:</Typography>

{/* Now render our images list. It will have 3 columns */}

<ImageList sx={{ width: 800, height: 450 }} cols={3} rowHeight={164}>

{/* Navigate through the images array. Each item corresponds to an ImageListItem component */}

{images.map((item) => (

<ImageListItem>

<img src={item.src} alt={item.alt} />

</ImageListItem>

))}

</ImageList>

</div>

);

 

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *