Example of React JS with Material UI components

This is an example of using Material Components in React JS
Demo

First, head over to nodejs.org and install Node if you already don't have it on your machine. Now, open up the Terminal on Mac or Command Prompt on Windows and run the following command to install create-react-app package.

npm install -g create-react-app

Create React App

Now, type the following command to create a new react app:

create-react-app materialdemo

Now, go to the project folder:

cd materialdemo

Install Dependencies required for this Project

npm install @material-ui/core
npm install @material-ui/icons
npm install date-fns@next -S
npm i @date-io/date-fns

After installation of above dependencies the package.json will get update as below

package.json

Example

{
  "name": "example5",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@date-io/date-fns": "^1.1.0",
    "@material-ui/core": "^3.9.3",
    "@material-ui/icons": "^3.0.2",
    "date-fns": "^2.0.0-alpha.27",
    "material-ui-pickers": "^2.2.4",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-router-dom": "^5.0.0",
    "react-scripts": "2.1.8"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

Tab Container

src\components\TabContainer\index.jsx

Example

import React from 'react';
import PropTypes from 'prop-types';
import Typography from '@material-ui/core/Typography';
 
 
function TabContainer(props) {
  return (
    <div>
      {props.children}
    </div>
  );
}
TabContainer.propTypes = {
  children: PropTypes.node.isRequired,
};
 
export default TabContainer;
 

Tabs Header

src\components\TabsDemo\index.jsx

Example

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
 
import TabContainer from '../TabContainer';
 
const styles = theme => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper,
  },
  colorPrimary: {
    color: "red",
  }
});
 
class TabsDemo extends React.Component {
  state = {
    activeTab: 1,
  };
 
  handleChange = (event, activeTab) => {
    this.setState( (state) => ({activeTab}));
  };
 
  render() {
    const { classes } = this.props;
    const { activeTab } = this.state;
 
    return (
      <div className={classes.root}>
        <AppBar position="static" className={classes.wrapped}>
          <Tabs value={activeTab} onChange={this.handleChange}>
            {
            this.props.tabs.map( tab => (
              <Tab
                key={tab.id}
                label={tab.label}
                value={tab.id}
                icon={tab.icon}
              />
            ))
            }
          </Tabs>
        </AppBar>
            {
              this.props.tabs.map( tab => (
                activeTab === tab.id
                  ? <TabContainer className={classes.wrapper} key={tab.id}>{tab.component}</TabContainer>
                  : null
              ))
            }
      </div>
    );
  }
}
 
TabsDemo.propTypes = {
  classes: PropTypes.object.isRequired,
  tabs: PropTypes.arrayOf(
    PropTypes.shape({
      label: PropTypes.string.isRequired,
      id: PropTypes.number.isRequired,
      component: PropTypes.object.isRequired,
    }).isRequired)
    .isRequired,
};
 
export default withStyles(styles)(TabsDemo);

Demo Style for modal pop-up

src\components\DemoStyle\index.jsx

Example

import React from 'react';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import cyan from '@material-ui/core/colors/cyan';
import green from '@material-ui/core/colors/green';
import CssBaseline from '@material-ui/core/CssBaseline';
 
const theme = createMuiTheme({
  palette: {
    primary: {
      light: cyan[300],
      main: cyan[500],
      dark: cyan[700],
    },
    secondary: {
      light: green[300],
      main: green[500],
      dark: green[700],
    },
  },
  typography: {
    useNextVariants: true,
  },
});
 
function DemoStyle(Component) {
  function DemoStyle(props) {
    return (
		<MuiThemeProvider theme={theme}>    
		<CssBaseline />
		<Component {...props} />
		</MuiThemeProvider>
	);
  }
  return DemoStyle;
}
 
export default DemoStyle;

Modal Pop-up UI

src\components\ModalDemo\index.jsx

Example

import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogActions from '@material-ui/core/DialogActions';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
import DemoStyle from '../DemoStyle';
 
const styles = theme => ({
  root: {
    textAlign: 'center',
    paddingTop: theme.spacing.unit * 20,
  },
});
 
class ModalDemo extends React.Component {
  state = {
    open: false,
  };
 
  handleClose = () => {
    this.setState({
      open: false,
    });
  };
 
  handleClick = () => {
    this.setState({
      open: true,
    });
  };
 
  render() {
    const { classes } = this.props;
    const { open } = this.state;
 
    return (
      <div className={classes.root}>
        <Dialog open={open} onClose={this.handleClose}>
          <DialogTitle>Modal Pop-up</DialogTitle>
          <DialogContent>
            <DialogContentText>This is an example of modal pop-up</DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button color="primary" onClick={this.handleClose}>
              OK
            </Button>
          </DialogActions>
        </Dialog>
        <Typography variant="h3" gutterBottom>
          Material-UI Demo
        </Typography>
        <Typography variant="subtitle1" gutterBottom>
          Example Project
        </Typography>
        <Button variant="contained" color="secondary" onClick={this.handleClick}>
          Show Pop-Up
        </Button>
      </div>
    );
  }
}
 
ModalDemo.propTypes = {
  classes: PropTypes.object.isRequired,
};
 
export default DemoStyle(withStyles(styles)(ModalDemo));

Grid Listing UI

src\components\GridListDemo\index.jsx

Example

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import GridList from '@material-ui/core/GridList';
import GridListTile from '@material-ui/core/GridListTile';
import GridListTileBar from '@material-ui/core/GridListTileBar';
import ListSubheader from '@material-ui/core/ListSubheader';
import IconButton from '@material-ui/core/IconButton';
import InfoIcon from '@material-ui/icons/Info';
 
import one from './img/1.png';
import two from './img/2.png';
import three from './img/3.png';
import four from './img/4.png';
 
const styles = theme => ({
  root: {
    display: 'flex',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
    overflow: 'hidden',
    backgroundColor: theme.palette.background.paper,
  },
  gridList: {
    width: 500,
    height: 500,
  },
  icon: {
    color: 'rgba(255, 255, 255, 0.54)',
  },
});
 
 
 
const tileData = [
  {
    img: one,
    title: 'Test1',
    author: 'Data for test1',
  },
  {
    img: two,
    title: 'Test2',
    author: 'Data for test2',
  },
  {
    img: three,
    title: 'Test3',
    author: 'Data for test3',
  },
  {
    img: four,
    title: 'Test4',
    author: 'Data for test4',
  },
];
function GridListDemo(props) {
  const { classes } = props;
 
  return (
    <div className={classes.root}>
      <GridList cellHeight={200} cellWidth={200} className={classes.gridList}>
        <GridListTile key="Subheader" cols={2} style={{ height: 'auto' }}>
          <ListSubheader component="div">Image gridlist</ListSubheader>
        </GridListTile>
        {tileData.map(tile => (
          <GridListTile key={tile.img}>
            <img src={tile.img} alt={tile.title} />
            <GridListTileBar
              title={tile.title}
              subtitle={<span>by: {tile.author}</span>}
              actionIcon={
                <IconButton className={classes.icon}>
                  <InfoIcon />
                </IconButton>
                }
            />
          </GridListTile>
        ))}
      </GridList>
    </div>
  );
}
 
GridListDemo.propTypes = {
  classes: PropTypes.object.isRequired,
};
 
export default withStyles(styles)(GridListDemo);

Create folder src\components\GridListDemo\img and upload 4 different images with name 1.png, 2.png, 3.png and 4.png


Date and Time Picker

src\components\DateTimePickersDemo\index.jsx

Example

import React from 'react';
import PropTypes from 'prop-types';
import Grid from '@material-ui/core/Grid';
import { withStyles } from '@material-ui/core/styles';
import DateFnsUtils from '@date-io/date-fns';
import { MuiPickersUtilsProvider, TimePicker, DatePicker } from 'material-ui-pickers';
 
const styles = {
  grid: {
    width: '60%',
  },
};
 
class MaterialUIPickersDemo extends React.Component {
  state = {
    selectedDate: new Date('2019-03-31T21:11:54'),
  };
 
  handleDateChange = date => {
    this.setState({ selectedDate: date });
  };
 
  render() {
    const { classes } = this.props;
    const { selectedDate } = this.state;
 
    return (
      <MuiPickersUtilsProvider utils={DateFnsUtils}>
        <Grid container className={classes.grid} justify="space-around">
          <DatePicker
            margin="normal"
            label="Date picker"
            value={selectedDate}
            onChange={this.handleDateChange}
          />
          <TimePicker
            margin="normal"
            label="Time picker"
            value={selectedDate}
            onChange={this.handleDateChange}
          />
        </Grid>
      </MuiPickersUtilsProvider>
    );
  }
}
 
MaterialUIPickersDemo.propTypes = {
  classes: PropTypes.object.isRequired,
};
 
export default withStyles(styles)(MaterialUIPickersDemo);

Update App.js to load all Material UI components

src\App.js

Example

import React, { Component } from 'react';
import './App.css';
import HomeIcon from '@material-ui/icons/Home';
import AddCommentIcon from '@material-ui/icons/AddComment';
import BorderClearIcon from '@material-ui/icons/BorderClear';
import DateRangeIcon from '@material-ui/icons/DateRange';
 
 
import TabsDemo from './components/TabsDemo';
import ModalDemo from './components/ModalDemo';
import GridListDemo from './components/GridListDemo'
import DateTimePickersDemo from './components/DateTimePickersDemo';
 
class App extends Component {
  render() {
    return (
      <div className="App">
        <TabsDemo tabs={tabs} />
      </div>
    );
  }
}
 
export default App;
 
 
const tabs = [
  {
    id: 1,
    label: 'Home',
    component: <TabsDemo tabs={[{
      id: 2,
      label: 'Modal',
      component: <ModalDemo />,
      icon: <AddCommentIcon />
    },
      {
        id: 3,
        label: 'GridList',
        component: <GridListDemo />,
        icon: <BorderClearIcon />
      },]} />,
    icon: <HomeIcon />
  },
  {
    id: 2,
    label: 'Modal',
    component: <ModalDemo />,
    icon: <AddCommentIcon />
  },
  {
    id: 3,
    label: 'GridList',
    component: <GridListDemo />,
    icon: <BorderClearIcon />
  },
  {
    id: 4,
    label: 'DatePickers',
    component: <DateTimePickersDemo />,
    icon: <DateRangeIcon />
  },
]

Final folder structure would be as below

Example


Deprecated: Array and string offset access syntax with curly braces is deprecated in /home/golayrva/public_html/lib/Varien/Filter/Template/Tokenizer/Abstract.php on line 89


Now launch the application

npm start

This will developed a static website on web server on port 3000 on your machine. This also launch your browser navigating to http://localhost:3000.


Most Helpful This Week