ReactJS - Material UI


Advertisements

React community provides a huge collection of advanced UI component framework. Material UI is one of the popular React UI frameworks. Let us learn how to use material UI library in this chapter.

Installation

Material UI can be installed using npm package.

npm install @material-ui/core

Material UI recommends roboto fonts for UI. To use Roboto font, include it using Gooogleapi links.

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />

To use font icons, use icon link from googleapis −

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />

To use SVG icons, install @material-ui/icons package −

npm install @material-ui/icons

Working example

Let us recreate the expense list application and use material ui components instead of html tables.

First, create a new react application, react-materialui-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter.

Next, install React Transition Group library −

cd /go/to/project npm install @material-ui/core @material-ui/icons --save

Next, open the application in your favorite editor.

Next, create src folder under the root directory of the application.

Next, create components folder under src folder.

Next, create a file, ExpenseEntryItemList.js in src/components folder to create ExpenseEntryItemList component

Next, import React library and the stylesheet.

import React from 'react';

Next, import Material-UI library.

import { withStyles } from '@material-ui/core/styles'; 
import Table from '@material-ui/core/Table'; 
import TableBody from '@material-ui/core/TableBody'; 
import TableCell from '@material-ui/core/TableCell'; 
import TableContainer from '@material-ui/core/TableContainer'; 
import TableHead from '@material-ui/core/TableHead'; 
import TableRow from '@material-ui/core/TableRow'; 
import Paper from '@material-ui/core/Paper';

Next, create ExpenseEntryItemList class and call constructor function.

class ExpenseEntryItemList extends React.Component {
   constructor(props) {
      super(props);
   }
}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />

Next, create a render function.

render() { 
}

Next, apply styles for table rows and table cells in the render method.

const StyledTableCell = withStyles((theme) => ({
   head: {
      backgroundColor: theme.palette.common.black,
      color: theme.palette.common.white,
   },
   body: {
      fontSize: 14,
   },
}))(TableCell);
const StyledTableRow = withStyles((theme) => ({
   root: {
      '&:nth-of-type(odd)': {
         backgroundColor: theme.palette.action.hover,
      },
   },
}))(TableRow);

Next, Use map method to generate a collection of Material UI StyledTableRow each representing a single expense entry item in the list.

const lists = this.props.items.map((item) =>
   <StyledTableRow key={item.id}>
      <StyledTableCell component="th" scope="row">
         {item.name}
      </StyledTableCell>
      <StyledTableCell align="right">{item.amount}</StyledTableCell>
      <StyledTableCell align="right">
         {new Date(item.spendDate).toDateString()}
      </StyledTableCell>
      <StyledTableCell align="right">{item.category}</StyledTableCell>
   </StyledTableRow>
);

Here, key identifies each row and it has to be unique among the list.

Next, in the render() method, create a Material UI table and include the lists expression in the rows section and return it.

return (
<TableContainer component={Paper}>
   <Table aria-label="customized table">
      <TableHead>
         <TableRow>
            <StyledTableCell>Title</StyledTableCell>
            <StyledTableCell align="right">Amount</StyledTableCell>
            <StyledTableCell align="right">Spend date</StyledTableCell>
            <StyledTableCell align="right">Category</StyledTableCell>
         </TableRow>
      </TableHead>
      <TableBody>
         {lists}
      </TableBody>
   </Table>
</TableContainer> );

Finally, export the component.

export default ExpenseEntryItemList;

Now, we have successfully created the component to render the expense items using material ui components.

The complete source code of the component is as given below −

import React from 'react';

import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';

class ExpenseEntryItemList extends React.Component {
   constructor(props) {
      super(props);
   }
   render() {
      const StyledTableCell = withStyles((theme) => ({
         head: {
            backgroundColor: theme.palette.common.black,
            color: theme.palette.common.white,
         },
         body: {
            fontSize: 14,
         },
      }))(TableCell);
      const StyledTableRow = withStyles((theme) => ({
         root: {
            '&:nth-of-type(odd)': {
               backgroundColor: theme.palette.action.hover,
            },
         },
      }))(TableRow);
      const lists = this.props.items.map((item) =>
         <StyledTableRow key={item.id}>
            <StyledTableCell component="th" scope="row">
               {item.name}
            </StyledTableCell>
            <StyledTableCell align="right">{item.amount}</StyledTableCell>
            <StyledTableCell align="right">{new Date(item.spendDate).toDateString()}</StyledTableCell>
            <StyledTableCell align="right">{item.category}</StyledTableCell>
         </StyledTableRow>
      );
      return (
      <TableContainer component={Paper}>
         <Table aria-label="customized table">
            <TableHead>
               <TableRow>
                  <StyledTableCell>Title</StyledTableCell>
                  <StyledTableCell align="right">Amount</StyledTableCell>
                  <StyledTableCell align="right">Spend date</StyledTableCell>
                  <StyledTableCell align="right">Category</StyledTableCell>
               </TableRow>
            </TableHead>
            <TableBody>
               {lists}
            </TableBody>
         </Table>
      </TableContainer> );
   }
}
export default ExpenseEntryItemList;

Next, open index.js and import react library and our newly created ExpenseEntryItemList component.

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import ExpenseEntryItemList from './components/ExpenseEntryItemList';

Next, declare a list (of expense entry item) and populate it with some random values in index.js file.

const items = [
   { id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" },
   { id: 1, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" },
   { id: 1, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" },
   { id: 1, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" },
   { id: 1, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" },
   { id: 1, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" },
   { id: 1, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" },
   { id: 1, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" },
   { id: 1, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" },
   { id: 1, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" }
]

Next, use ExpenseEntryItemList component by passing the items through items attributes.

ReactDOM.render(
   <React.StrictMode>
      <ExpenseEntryItemList items={items} />
   </React.StrictMode>,
   document.getElementById('root')
);

The complete code of index.js is as follows −

import React from 'react';
import ReactDOM from 'react-dom';
import ExpenseEntryItemList from './components/ExpenseEntryItemList';

const items = [
   { id: 1, name: "Pizza", amount: 80, spendDate: "2020-10-10", category: "Food" },
   { id: 1, name: "Grape Juice", amount: 30, spendDate: "2020-10-12", category: "Food" },
   { id: 1, name: "Cinema", amount: 210, spendDate: "2020-10-16", category: "Entertainment" },
   { id: 1, name: "Java Programming book", amount: 242, spendDate: "2020-10-15", category: "Academic" },
   { id: 1, name: "Mango Juice", amount: 35, spendDate: "2020-10-16", category: "Food" },
   { id: 1, name: "Dress", amount: 2000, spendDate: "2020-10-25", category: "Cloth" },
   { id: 1, name: "Tour", amount: 2555, spendDate: "2020-10-29", category: "Entertainment" },
   { id: 1, name: "Meals", amount: 300, spendDate: "2020-10-30", category: "Food" },
   { id: 1, name: "Mobile", amount: 3500, spendDate: "2020-11-02", category: "Gadgets" },
   { id: 1, name: "Exam Fees", amount: 1245, spendDate: "2020-11-04", category: "Academic" }
]
ReactDOM.render(
   <React.StrictMode>
      <ExpenseEntryItemList items={items} />
   </React.StrictMode>,
   document.getElementById('root')
);

Next, serve the application using npm command.

npm start

Next, open index.html file in the public folder and include the material UI font and icons.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>Material UI App</title>
      <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
      <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
   </head>
   <body>
      <div id="root"></div>
      <script type="text/JavaScript" src="./index.js"></script>
   </body>
</html>

Next, open the browser and enter http://localhost:3000 in the address bar and press enter.

material UI
reactjs_state.htm
Advertisements