Material-UI Code Snippets
🎨

Material-UI Code Snippets

Tags
React.js
MUI
Published
Author
 
 

Installation

bashCopy code npm install @mui/material @emotion/react @emotion/styled

Basic Usage

jsxCopy code import React from 'react'; import { Button, TextField, AppBar, Toolbar, Typography } from '@mui/material'; const MyComponent = () => { return ( <div> <Button variant="contained" color="primary"> Click me </Button> <TextField label="Enter text" variant="outlined" /> <AppBar position="static"> <Toolbar> <Typography variant="h6">My App</Typography> </Toolbar> </AppBar> </div> ); };

Styling with makeStyles

jsxCopy code import { makeStyles } from '@mui/styles'; const useStyles = makeStyles((theme) => ({ root: { backgroundColor: theme.palette.background.paper, padding: theme.spacing(2), }, button: { margin: theme.spacing(1), }, })); const StyledComponent = () => { const classes = useStyles(); return ( <div className={classes.root}> <Button className={classes.button} variant="contained" color="primary"> Styled Button </Button> </div> ); };

Grid System

jsxCopy code import { Grid } from '@mui/material'; const GridExample = () => { return ( <Grid container spacing={2}> <Grid item xs={12} sm={6} md={4}> {/* Content goes here */} </Grid> <Grid item xs={12} sm={6} md={4}> {/* Content goes here */} </Grid> <Grid item xs={12} sm={6} md={4}> {/* Content goes here */} </Grid> </Grid> ); };

Theme Customization

jsxCopy code import { createTheme, ThemeProvider } from '@mui/material/styles'; const theme = createTheme({ palette: { primary: { main: '#007bff', }, secondary: { main: '#ff4500', }, }, }); const ThemedComponent = () => { return ( <ThemeProvider theme={theme}> {/* Your components go here */} </ThemeProvider> ); };
Remember to check the official documentation for the latest updates and more in-depth information.
 

Dialogs

jsxCopy code import { Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material'; const MyDialog = ({ open, handleClose }) => { return ( <Dialog open={open} onClose={handleClose}> <DialogTitle>Dialog Title</DialogTitle> <DialogContent> {/* Dialog content goes here */} </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> Cancel </Button> <Button onClick={handleClose} color="primary"> Save </Button> </DialogActions> </Dialog> ); };

Tabs

jsxCopy code import { Tab, Tabs } from '@mui/material'; const MyTabs = () => { const [value, setValue] = React.useState(0); const handleChange = (event, newValue) => { setValue(newValue); }; return ( <Tabs value={value} onChange={handleChange} centered> <Tab label="Tab 1" /> <Tab label="Tab 2" /> <Tab label="Tab 3" /> </Tabs> ); };

Icons

jsxCopy code import { IconButton } from '@mui/material'; import DeleteIcon from '@mui/icons-material/Delete'; const MyIconButton = () => { return ( <IconButton color="primary" aria-label="delete"> <DeleteIcon /> </IconButton> ); };

Snackbar

jsxCopy code import { Snackbar, Alert } from '@mui/material'; const MySnackbar = ({ open, handleClose }) => { return ( <Snackbar open={open} autoHideDuration={6000} onClose={handleClose}> <Alert onClose={handleClose} severity="success"> This is a success message! </Alert> </Snackbar> ); };

Typography

jsxCopy code import { Typography } from '@mui/material'; const MyTypography = () => { return ( <div> <Typography variant="h1">Heading 1</Typography> <Typography variant="body1">Body text goes here.</Typography> </div> ); };

Expansion Panels

jsxCopy code import { ExpansionPanel, ExpansionPanelSummary, ExpansionPanelDetails, Typography } from '@mui/material'; import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; const MyExpansionPanel = () => { return ( <ExpansionPanel> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography>Panel Title</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> {/* Panel content goes here */} </ExpansionPanelDetails> </ExpansionPanel> ); };

List

jsxCopy code import { List, ListItem, ListItemText, ListItemIcon } from '@mui/material'; import InboxIcon from '@mui/icons-material/Inbox'; const MyList = () => { return ( <List> <ListItem button> <ListItemIcon> <InboxIcon /> </ListItemIcon> <ListItemText primary="Inbox" /> </ListItem> {/* Add more ListItems as needed */} </List> ); };

Select

jsxCopy code import { MenuItem, FormControl, Select, InputLabel } from '@mui/material'; const MySelect = () => { const [selectedValue, setSelectedValue] = React.useState(''); const handleChange = (event) => { setSelectedValue(event.target.value); }; return ( <FormControl> <InputLabel id="select-label">Select Option</InputLabel> <Select labelId="select-label" value={selectedValue} onChange={handleChange}> <MenuItem value="option1">Option 1</MenuItem> <MenuItem value="option2">Option 2</MenuItem> {/* Add more MenuItems as needed */} </Select> </FormControl> ); };

Card

jsxCopy code import { Card, CardContent, CardActions, Button, Typography } from '@mui/material'; const MyCard = () => { return ( <Card> <CardContent> <Typography variant="h5">Card Title</Typography> <Typography variant="body2">Card content goes here.</Typography> </CardContent> <CardActions> <Button size="small">Learn More</Button> </CardActions> </Card> ); };

Autocomplete

jsxCopy code import Autocomplete from '@mui/material/Autocomplete'; import TextField from '@mui/material/TextField'; const MyAutocomplete = () => { const options = ['Option 1', 'Option 2', 'Option 3']; return ( <Autocomplete options={options} renderInput={(params) => <TextField {...params} label="Choose an option" />} /> ); };

Date Picker

jsxCopy code import { MobileDatePicker } from '@mui/lab'; import TextField from '@mui/material/TextField'; const MyDatePicker = () => { const [selectedDate, handleDateChange] = React.useState(new Date()); return ( <MobileDatePicker label="Select Date" value={selectedDate} onChange={(date) => handleDateChange(date)} renderInput={(params) => <TextField {...params} />} /> ); };

Drawer

jsxCopy code import { Drawer, List, ListItem, ListItemText } from '@mui/material'; const MyDrawer = ({ isOpen, handleClose }) => { return ( <Drawer anchor="left" open={isOpen} onClose={handleClose}> <List> <ListItem button> <ListItemText primary="Item 1" /> </ListItem> <ListItem button> <ListItemText primary="Item 2" /> </ListItem> {/* Add more ListItems as needed */} </List> </Drawer> ); };

Tooltip

jsxCopy code import Tooltip from '@mui/material/Tooltip'; import IconButton from '@mui/material/IconButton'; import DeleteIcon from '@mui/icons-material/Delete'; const MyTooltip = () => { return ( <Tooltip title="Delete"> <IconButton color="primary"> <DeleteIcon /> </IconButton> </Tooltip> ); };

Snackbar with Action

jsxCopy code import { Snackbar, IconButton } from '@mui/material'; import CloseIcon from '@mui/icons-material/Close'; const MySnackbarWithAction = ({ open, handleClose }) => { return ( <Snackbar open={open} autoHideDuration={6000} onClose={handleClose} action={ <IconButton size="small" color="inherit" onClick={handleClose}> <CloseIcon fontSize="small" /> </IconButton> } > {/* Snackbar content goes here */} </Snackbar> ); };

Stepper

jsxCopy code import { Stepper, Step, StepLabel, Button } from '@mui/material'; const MyStepper = () => { const steps = ['Step 1', 'Step 2', 'Step 3']; const [activeStep, setActiveStep] = React.useState(0); const handleNext = () => { setActiveStep((prevActiveStep) => prevActiveStep + 1); }; const handleBack = () => { setActiveStep((prevActiveStep) => prevActiveStep - 1); }; return ( <div> <Stepper activeStep={activeStep} alternativeLabel> {steps.map((label) => ( <Step key={label}> <StepLabel>{label}</StepLabel> </Step> ))} </Stepper> <div> {activeStep === steps.length ? ( <div> <p>All steps completed</p> </div> ) : ( <div> <p>{steps[activeStep]}</p> <Button disabled={activeStep === 0} onClick={handleBack}> Back </Button> <Button variant="contained" color="primary" onClick={handleNext}> {activeStep === steps.length - 1 ? 'Finish' : 'Next'} </Button> </div> )} </div> </div> ); };

Pagination

jsxCopy code import { Pagination, Stack } from '@mui/material'; const MyPagination = () => { const handleChange = (event, value) => { // Handle page change }; return ( <Stack spacing={2}> <Pagination count={10} color="primary" onChange={handleChange} /> </Stack> ); };

Table

jsxCopy code import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@mui/material'; const MyTable = () => { const rows = [ { id: 1, name: 'Item 1', price: 10 }, { id: 2, name: 'Item 2', price: 20 }, // Add more rows as needed ]; return ( <TableContainer component={Paper}> <Table> <TableHead> <TableRow> <TableCell>ID</TableCell> <TableCell>Name</TableCell> <TableCell>Price</TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row) => ( <TableRow key={row.id}> <TableCell>{row.id}</TableCell> <TableCell>{row.name}</TableCell> <TableCell>{row.price}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ); };

AppBar with Tabs

jsxCopy code import { AppBar, Tabs, Tab } from '@mui/material'; const MyAppBarWithTabs = () => { const [value, setValue] = React.useState(0); const handleChange = (event, newValue) => { setValue(newValue); }; return ( <div> <AppBar position="static"> <Tabs value={value} onChange={handleChange}> <Tab label="Tab 1" /> <Tab label="Tab 2" /> <Tab label="Tab 3" /> </Tabs> </AppBar> {/* Tab panels go here */} </div> ); };

Accordion

jsxCopy code import { Accordion, AccordionSummary, AccordionDetails, Typography } from '@mui/material'; import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; const MyAccordion = () => { return ( <Accordion> <AccordionSummary expandIcon={<ExpandMoreIcon />}> <Typography>Accordion Title</Typography> </AccordionSummary> <AccordionDetails> {/* Accordion content goes here */} </AccordionDetails> </Accordion> ); };

Badge

jsxCopy code import Badge from '@mui/material/Badge'; import MailIcon from '@mui/icons-material/Mail'; const MyBadge = () => { return ( <Badge color="primary" badgeContent={4}> <MailIcon /> </Badge> ); };

Chip

jsxCopy code import Chip from '@mui/material/Chip'; const MyChip = () => { return ( <Chip label="Clickable Chip" onClick={() => console.log('Chip clicked')} /> ); };

Snackbar with Transition

jsxCopy code import { Snackbar, Slide } from '@mui/material'; const Transition = Slide; const MySnackbarWithTransition = ({ open, handleClose }) => { return ( <Snackbar open={open} autoHideDuration={6000} onClose={handleClose} TransitionComponent={Transition} message="Snackbar with Transition" /> ); };

Speed Dial

jsxCopy code import { SpeedDial, SpeedDialIcon, SpeedDialAction } from '@mui/material'; import EditIcon from '@mui/icons-material/Edit'; import DeleteIcon from '@mui/icons-material/Delete'; const MySpeedDial = () => { const actions = [ { icon: <EditIcon />, name: 'Edit' }, { icon: <DeleteIcon />, name: 'Delete' }, ]; return ( <SpeedDial ariaLabel="SpeedDial example" icon={<SpeedDialIcon />} direction="up" open={true} > {actions.map((action) => ( <SpeedDialAction key={action.name} icon={action.icon} tooltipTitle={action.name} /> ))} </SpeedDial> ); };

Divider

jsxCopy code import Divider from '@mui/material/Divider'; const MyDivider = () => { return <Divider />; };

Popover

jsxCopy code import { Popover, Typography, Button } from '@mui/material'; const MyPopover = () => { const [anchorEl, setAnchorEl] = React.useState(null); const handleClick = (event) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const open = Boolean(anchorEl); const id = open ? 'simple-popover' : undefined; return ( <div> <Button aria-describedby={id} variant="contained" onClick={handleClick}> Open Popover </Button> <Popover id={id} open={open} anchorEl={anchorEl} onClose={handleClose} anchorOrigin={{ vertical: 'bottom', horizontal: 'center', }} transformOrigin={{ vertical: 'top', horizontal: 'center', }} > <Typography>Popover Content</Typography> </Popover> </div> ); };

Toggle Button

jsxCopy code import { ToggleButton, ToggleButtonGroup } from '@mui/material'; import FormatBoldIcon from '@mui/icons-material/FormatBold'; import FormatItalicIcon from '@mui/icons-material/FormatItalic'; const MyToggleButtonGroup = () => { const [formats, setFormats] = React.useState(() => ['bold']); const handleFormat = (event, newFormats) => { setFormats(newFormats); }; return ( <ToggleButtonGroup value={formats} onChange={handleFormat} aria-label="text formatting"> <ToggleButton value="bold" aria-label="bold"> <FormatBoldIcon /> </ToggleButton> <ToggleButton value="italic" aria-label="italic"> <FormatItalicIcon /> </ToggleButton> </ToggleButtonGroup> ); };

Circular Progress

jsxCopy code import CircularProgress from '@mui/material/CircularProgress'; const MyCircularProgress = () => { return <CircularProgress />; };

Dialog with Form

jsxCopy code import { Dialog, DialogTitle, DialogContent, TextField, Button } from '@mui/material'; const MyDialogWithForm = ({ open, handleClose }) => { return ( <Dialog open={open} onClose={handleClose}> <DialogTitle>Form Dialog</DialogTitle> <DialogContent> <TextField label="Name" fullWidth /> {/* Add more form fields as needed */} </DialogContent> <div> <Button onClick={handleClose} color="primary"> Cancel </Button> <Button onClick={handleClose} color="primary"> Save </Button> </div> </Dialog> ); };

Radio Buttons

jsxCopy code import { Radio, RadioGroup, FormControlLabel, FormControl, FormLabel } from '@mui/material'; const MyRadioButtons = () => { const [selectedValue, setSelectedValue] = React.useState('option1'); const handleChange = (event) => { setSelectedValue(event.target.value); }; return ( <FormControl component="fieldset"> <FormLabel component="legend">Choose an option</FormLabel> <RadioGroup value={selectedValue} onChange={handleChange}> <FormControlLabel value="option1" control={<Radio />} label="Option 1" /> <FormControlLabel value="option2" control={<Radio />} label="Option 2" /> {/* Add more FormControlLabels as needed */} </RadioGroup> </FormControl> ); };

Select with Multiple Options

jsxCopy code import { MenuItem, FormControl, Select, InputLabel } from '@mui/material'; const MySelectMultiple = () => { const [selectedValues, setSelectedValues] = React.useState([]); const handleChange = (event) => { setSelectedValues(event.target.value); }; return ( <FormControl> <InputLabel id="select-multiple-label">Select Multiple Options</InputLabel> <Select labelId="select-multiple-label" multiple value={selectedValues} onChange={handleChange} > <MenuItem value="option1">Option 1</MenuItem> <MenuItem value="option2">Option 2</MenuItem> {/* Add more MenuItems as needed */} </Select> </FormControl> ); };

Pagination with Range

jsxCopy code import { Pagination, Stack } from '@mui/material'; const MyPaginationRange = () => { const handleChange = (event, value) => { // Handle page change }; return ( <Stack spacing={2}> <Pagination count={10} color="primary" page={5} onChange={handleChange} /> </Stack> ); };

Image

jsxCopy code import { Card, CardMedia, CardContent, Typography } from '@mui/material'; const MyImageCard = () => { return ( <Card> <CardMedia component="img" alt="Sample Image" height="140" image="https://source.unsplash.com/random" /> <CardContent> <Typography variant="h5">Image Card Title</Typography> <Typography variant="body2">Card content goes here.</Typography> </CardContent> </Card> ); };

Date Range Picker

jsxCopy code import { DesktopDateRangePicker } from '@mui/lab'; import TextField from '@mui/material/TextField'; const MyDateRangePicker = () => { const [value, setValue] = React.useState([null, null]); return ( <DesktopDateRangePicker startText="Start Date" endText="End Date" value={value} onChange={(newValue) => setValue(newValue)} renderInput={(startProps, endProps) => ( <> <TextField {...startProps} variant="outlined" margin="normal" helperText="" /> <TextField {...endProps} variant="outlined" margin="normal" helperText="" /> </> )} /> ); };