index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/NonInteractiveTooltips.js
import * as React from 'react'; import Button from '@mui/material/Button'; import Tooltip from '@mui/material/Tooltip'; export default function NonInteractiveTooltips() { return ( <Tooltip title="Add" disableInteractive> <Button>Not interactive</Button> </Tooltip> ); }
3,300
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/NonInteractiveTooltips.tsx
import * as React from 'react'; import Button from '@mui/material/Button'; import Tooltip from '@mui/material/Tooltip'; export default function NonInteractiveTooltips() { return ( <Tooltip title="Add" disableInteractive> <Button>Not interactive</Button> </Tooltip> ); }
3,301
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/NonInteractiveTooltips.tsx.preview
<Tooltip title="Add" disableInteractive> <Button>Not interactive</Button> </Tooltip>
3,302
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/PositionedTooltips.js
import * as React from 'react'; import Box from '@mui/material/Box'; import Grid from '@mui/material/Grid'; import Button from '@mui/material/Button'; import Tooltip from '@mui/material/Tooltip'; export default function PositionedTooltips() { return ( <Box sx={{ width: 500 }}> <Grid container justifyContent="center"> <Grid item> <Tooltip title="Add" placement="top-start"> <Button>top-start</Button> </Tooltip> <Tooltip title="Add" placement="top"> <Button>top</Button> </Tooltip> <Tooltip title="Add" placement="top-end"> <Button>top-end</Button> </Tooltip> </Grid> </Grid> <Grid container justifyContent="center"> <Grid item xs={6}> <Tooltip title="Add" placement="left-start"> <Button>left-start</Button> </Tooltip> <br /> <Tooltip title="Add" placement="left"> <Button>left</Button> </Tooltip> <br /> <Tooltip title="Add" placement="left-end"> <Button>left-end</Button> </Tooltip> </Grid> <Grid item container xs={6} alignItems="flex-end" direction="column"> <Grid item> <Tooltip title="Add" placement="right-start"> <Button>right-start</Button> </Tooltip> </Grid> <Grid item> <Tooltip title="Add" placement="right"> <Button>right</Button> </Tooltip> </Grid> <Grid item> <Tooltip title="Add" placement="right-end"> <Button>right-end</Button> </Tooltip> </Grid> </Grid> </Grid> <Grid container justifyContent="center"> <Grid item> <Tooltip title="Add" placement="bottom-start"> <Button>bottom-start</Button> </Tooltip> <Tooltip title="Add" placement="bottom"> <Button>bottom</Button> </Tooltip> <Tooltip title="Add" placement="bottom-end"> <Button>bottom-end</Button> </Tooltip> </Grid> </Grid> </Box> ); }
3,303
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/PositionedTooltips.tsx
import * as React from 'react'; import Box from '@mui/material/Box'; import Grid from '@mui/material/Grid'; import Button from '@mui/material/Button'; import Tooltip from '@mui/material/Tooltip'; export default function PositionedTooltips() { return ( <Box sx={{ width: 500 }}> <Grid container justifyContent="center"> <Grid item> <Tooltip title="Add" placement="top-start"> <Button>top-start</Button> </Tooltip> <Tooltip title="Add" placement="top"> <Button>top</Button> </Tooltip> <Tooltip title="Add" placement="top-end"> <Button>top-end</Button> </Tooltip> </Grid> </Grid> <Grid container justifyContent="center"> <Grid item xs={6}> <Tooltip title="Add" placement="left-start"> <Button>left-start</Button> </Tooltip> <br /> <Tooltip title="Add" placement="left"> <Button>left</Button> </Tooltip> <br /> <Tooltip title="Add" placement="left-end"> <Button>left-end</Button> </Tooltip> </Grid> <Grid item container xs={6} alignItems="flex-end" direction="column"> <Grid item> <Tooltip title="Add" placement="right-start"> <Button>right-start</Button> </Tooltip> </Grid> <Grid item> <Tooltip title="Add" placement="right"> <Button>right</Button> </Tooltip> </Grid> <Grid item> <Tooltip title="Add" placement="right-end"> <Button>right-end</Button> </Tooltip> </Grid> </Grid> </Grid> <Grid container justifyContent="center"> <Grid item> <Tooltip title="Add" placement="bottom-start"> <Button>bottom-start</Button> </Tooltip> <Tooltip title="Add" placement="bottom"> <Button>bottom</Button> </Tooltip> <Tooltip title="Add" placement="bottom-end"> <Button>bottom-end</Button> </Tooltip> </Grid> </Grid> </Box> ); }
3,304
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/TransitionsTooltips.js
import * as React from 'react'; import Button from '@mui/material/Button'; import Tooltip from '@mui/material/Tooltip'; import Fade from '@mui/material/Fade'; import Zoom from '@mui/material/Zoom'; export default function TransitionsTooltips() { return ( <div> <Tooltip title="Add"> <Button>Grow</Button> </Tooltip> <Tooltip TransitionComponent={Fade} TransitionProps={{ timeout: 600 }} title="Add" > <Button>Fade</Button> </Tooltip> <Tooltip TransitionComponent={Zoom} title="Add"> <Button>Zoom</Button> </Tooltip> </div> ); }
3,305
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/TransitionsTooltips.tsx
import * as React from 'react'; import Button from '@mui/material/Button'; import Tooltip from '@mui/material/Tooltip'; import Fade from '@mui/material/Fade'; import Zoom from '@mui/material/Zoom'; export default function TransitionsTooltips() { return ( <div> <Tooltip title="Add"> <Button>Grow</Button> </Tooltip> <Tooltip TransitionComponent={Fade} TransitionProps={{ timeout: 600 }} title="Add" > <Button>Fade</Button> </Tooltip> <Tooltip TransitionComponent={Zoom} title="Add"> <Button>Zoom</Button> </Tooltip> </div> ); }
3,306
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/TransitionsTooltips.tsx.preview
<Tooltip title="Add"> <Button>Grow</Button> </Tooltip> <Tooltip TransitionComponent={Fade} TransitionProps={{ timeout: 600 }} title="Add" > <Button>Fade</Button> </Tooltip> <Tooltip TransitionComponent={Zoom} title="Add"> <Button>Zoom</Button> </Tooltip>
3,307
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/TriggersTooltips.js
import * as React from 'react'; import Grid from '@mui/material/Grid'; import Button from '@mui/material/Button'; import Tooltip from '@mui/material/Tooltip'; import ClickAwayListener from '@mui/material/ClickAwayListener'; export default function TriggersTooltips() { const [open, setOpen] = React.useState(false); const handleTooltipClose = () => { setOpen(false); }; const handleTooltipOpen = () => { setOpen(true); }; return ( <div> <Grid container justifyContent="center"> <Grid item> <Tooltip disableFocusListener title="Add"> <Button>Hover or touch</Button> </Tooltip> </Grid> <Grid item> <Tooltip disableHoverListener title="Add"> <Button>Focus or touch</Button> </Tooltip> </Grid> <Grid item> <Tooltip disableFocusListener disableTouchListener title="Add"> <Button>Hover</Button> </Tooltip> </Grid> <Grid item> <ClickAwayListener onClickAway={handleTooltipClose}> <div> <Tooltip PopperProps={{ disablePortal: true, }} onClose={handleTooltipClose} open={open} disableFocusListener disableHoverListener disableTouchListener title="Add" > <Button onClick={handleTooltipOpen}>Click</Button> </Tooltip> </div> </ClickAwayListener> </Grid> </Grid> </div> ); }
3,308
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/TriggersTooltips.tsx
import * as React from 'react'; import Grid from '@mui/material/Grid'; import Button from '@mui/material/Button'; import Tooltip from '@mui/material/Tooltip'; import ClickAwayListener from '@mui/material/ClickAwayListener'; export default function TriggersTooltips() { const [open, setOpen] = React.useState(false); const handleTooltipClose = () => { setOpen(false); }; const handleTooltipOpen = () => { setOpen(true); }; return ( <div> <Grid container justifyContent="center"> <Grid item> <Tooltip disableFocusListener title="Add"> <Button>Hover or touch</Button> </Tooltip> </Grid> <Grid item> <Tooltip disableHoverListener title="Add"> <Button>Focus or touch</Button> </Tooltip> </Grid> <Grid item> <Tooltip disableFocusListener disableTouchListener title="Add"> <Button>Hover</Button> </Tooltip> </Grid> <Grid item> <ClickAwayListener onClickAway={handleTooltipClose}> <div> <Tooltip PopperProps={{ disablePortal: true, }} onClose={handleTooltipClose} open={open} disableFocusListener disableHoverListener disableTouchListener title="Add" > <Button onClick={handleTooltipOpen}>Click</Button> </Tooltip> </div> </ClickAwayListener> </Grid> </Grid> </div> ); }
3,309
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/VariableWidth.js
import * as React from 'react'; import { styled } from '@mui/material/styles'; import Button from '@mui/material/Button'; import Tooltip, { tooltipClasses } from '@mui/material/Tooltip'; const CustomWidthTooltip = styled(({ className, ...props }) => ( <Tooltip {...props} classes={{ popper: className }} /> ))({ [`& .${tooltipClasses.tooltip}`]: { maxWidth: 500, }, }); const NoMaxWidthTooltip = styled(({ className, ...props }) => ( <Tooltip {...props} classes={{ popper: className }} /> ))({ [`& .${tooltipClasses.tooltip}`]: { maxWidth: 'none', }, }); const longText = ` Aliquam eget finibus ante, non facilisis lectus. Sed vitae dignissim est, vel aliquam tellus. Praesent non nunc mollis, fermentum neque at, semper arcu. Nullam eget est sed sem iaculis gravida eget vitae justo. `; export default function VariableWidth() { return ( <div> <Tooltip title={longText}> <Button sx={{ m: 1 }}>Default Width [300px]</Button> </Tooltip> <CustomWidthTooltip title={longText}> <Button sx={{ m: 1 }}>Custom Width [500px]</Button> </CustomWidthTooltip> <NoMaxWidthTooltip title={longText}> <Button sx={{ m: 1 }}>No wrapping</Button> </NoMaxWidthTooltip> </div> ); }
3,310
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/VariableWidth.tsx
import * as React from 'react'; import { styled } from '@mui/material/styles'; import Button from '@mui/material/Button'; import Tooltip, { TooltipProps, tooltipClasses } from '@mui/material/Tooltip'; const CustomWidthTooltip = styled(({ className, ...props }: TooltipProps) => ( <Tooltip {...props} classes={{ popper: className }} /> ))({ [`& .${tooltipClasses.tooltip}`]: { maxWidth: 500, }, }); const NoMaxWidthTooltip = styled(({ className, ...props }: TooltipProps) => ( <Tooltip {...props} classes={{ popper: className }} /> ))({ [`& .${tooltipClasses.tooltip}`]: { maxWidth: 'none', }, }); const longText = ` Aliquam eget finibus ante, non facilisis lectus. Sed vitae dignissim est, vel aliquam tellus. Praesent non nunc mollis, fermentum neque at, semper arcu. Nullam eget est sed sem iaculis gravida eget vitae justo. `; export default function VariableWidth() { return ( <div> <Tooltip title={longText}> <Button sx={{ m: 1 }}>Default Width [300px]</Button> </Tooltip> <CustomWidthTooltip title={longText}> <Button sx={{ m: 1 }}>Custom Width [500px]</Button> </CustomWidthTooltip> <NoMaxWidthTooltip title={longText}> <Button sx={{ m: 1 }}>No wrapping</Button> </NoMaxWidthTooltip> </div> ); }
3,311
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/VariableWidth.tsx.preview
<Tooltip title={longText}> <Button sx={{ m: 1 }}>Default Width [300px]</Button> </Tooltip> <CustomWidthTooltip title={longText}> <Button sx={{ m: 1 }}>Custom Width [500px]</Button> </CustomWidthTooltip> <NoMaxWidthTooltip title={longText}> <Button sx={{ m: 1 }}>No wrapping</Button> </NoMaxWidthTooltip>
3,312
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/tooltips/tooltips.md
--- productId: material-ui title: React Tooltip component components: Tooltip githubLabel: 'component: tooltip' materialDesign: https://m2.material.io/components/tooltips waiAria: https://www.w3.org/WAI/ARIA/apg/patterns/tooltip/ --- # Tooltip <p class="description">Tooltips display informative text when users hover over, focus on, or tap an element.</p> When activated, Tooltips display a text label identifying an element, such as a description of its function. {{"component": "modules/components/ComponentLinkHeader.js"}} ## Basic tooltip {{"demo": "BasicTooltip.js"}} ## Positioned tooltips The `Tooltip` has 12 **placement** choices. They don't have directional arrows; instead, they rely on motion emanating from the source to convey direction. {{"demo": "PositionedTooltips.js"}} ## Customization Here are some examples of customizing the component. You can learn more about this in the [overrides documentation page](/material-ui/customization/how-to-customize/). {{"demo": "CustomizedTooltips.js"}} ## Arrow tooltips You can use the `arrow` prop to give your tooltip an arrow indicating which element it refers to. {{"demo": "ArrowTooltips.js"}} ## Custom child element The tooltip needs to apply DOM event listeners to its child element. If the child is a custom React element, you need to make sure that it spreads its props to the underlying DOM element. ```jsx const MyComponent = React.forwardRef(function MyComponent(props, ref) { // Spread the props to the underlying DOM element. return ( <div {...props} ref={ref}> Bin </div> ); }); // ... <Tooltip title="Delete"> <MyComponent /> </Tooltip>; ``` You can find a similar concept in the [wrapping components](/material-ui/guides/composition/#wrapping-components) guide. If using a class component as a child, you'll also need to ensure that the ref is forwarded to the underlying DOM element. (A ref to the class component itself will not work.) ```jsx class MyComponent extends React.Component { render() { const { innerRef, ...props } = this.props; // Spread the props to the underlying DOM element. return ( <div {...props} ref={innerRef}> Bin </div> ); } } // Wrap MyComponent to forward the ref as expected by Tooltip const WrappedMyComponent = React.forwardRef(function WrappedMyComponent(props, ref) { return <MyComponent {...props} innerRef={ref} />; }); // ... <Tooltip title="Delete"> <WrappedMyComponent /> </Tooltip>; ``` ## Triggers You can define the types of events that cause a tooltip to show. The touch action requires a long press due to the `enterTouchDelay` prop being set to `700`ms by default. {{"demo": "TriggersTooltips.js"}} ## Controlled tooltips You can use the `open`, `onOpen` and `onClose` props to control the behavior of the tooltip. {{"demo": "ControlledTooltips.js"}} ## Variable width The `Tooltip` wraps long text by default to make it readable. {{"demo": "VariableWidth.js"}} ## Interactive Tooltips are interactive by default (to pass [WCAG 2.1 success criterion 1.4.13](https://www.w3.org/TR/WCAG21/#content-on-hover-or-focus)). It won't close when the user hovers over the tooltip before the `leaveDelay` is expired. You can disable this behavior (thus failing the success criterion which is required to reach level AA) by passing `disableInteractive`. {{"demo": "NonInteractiveTooltips.js"}} ## Disabled elements By default disabled elements like `<button>` do not trigger user interactions so a `Tooltip` will not activate on normal events like hover. To accommodate disabled elements, add a simple wrapper element, such as a `span`. :::warning In order to work with Safari, you need at least one display block or flex item below the tooltip wrapper. ::: {{"demo": "DisabledTooltips.js"}} :::warning If you're not wrapping a Material UI component that inherits from `ButtonBase`, for instance, a native `<button>` element, you should also add the CSS property _pointer-events: none;_ to your element when disabled: ::: ```jsx <Tooltip title="You don't have permission to do this"> <span> <button disabled={disabled} style={disabled ? { pointerEvents: 'none' } : {}}> A disabled button </button> </span> </Tooltip> ``` ## Transitions Use a different transition. {{"demo": "TransitionsTooltips.js"}} ## Follow cursor You can enable the tooltip to follow the cursor by setting `followCursor={true}`. {{"demo": "FollowCursorTooltips.js"}} ## Virtual element In the event you need to implement a custom placement, you can use the `anchorEl` prop: The value of the `anchorEl` prop can be a reference to a fake DOM element. You need to create an object shaped like the [`VirtualElement`](https://popper.js.org/docs/v2/virtual-elements/). {{"demo": "AnchorElTooltips.js"}} ## Showing and hiding The tooltip is normally shown immediately when the user's mouse hovers over the element, and hides immediately when the user's mouse leaves. A delay in showing or hiding the tooltip can be added through the `enterDelay` and `leaveDelay` props, as shown in the Controlled Tooltips demo above. On mobile, the tooltip is displayed when the user longpresses the element and hides after a delay of 1500ms. You can disable this feature with the `disableTouchListener` prop. {{"demo": "DelayTooltips.js"}} ## Accessibility (WAI-ARIA: https://www.w3.org/WAI/ARIA/apg/patterns/tooltip/) By default, the tooltip only labels its child element. This is notably different from `title` which can either label **or** describe its child depending on whether the child already has a label. For example, in: ```html <button title="some more information">A button</button> ``` the `title` acts as an accessible description. If you want the tooltip to act as an accessible description you can pass `describeChild`. Note that you shouldn't use `describeChild` if the tooltip provides the only visual label. Otherwise, the child would have no accessible name and the tooltip would violate [success criterion 2.5.3 in WCAG 2.1](https://www.w3.org/WAI/WCAG21/Understanding/label-in-name.html). {{"demo": "AccessibilityTooltips.js"}}
3,313
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transfer-list/SelectAllTransferList.js
import * as React from 'react'; import Grid from '@mui/material/Grid'; import List from '@mui/material/List'; import Card from '@mui/material/Card'; import CardHeader from '@mui/material/CardHeader'; import ListItem from '@mui/material/ListItem'; import ListItemText from '@mui/material/ListItemText'; import ListItemIcon from '@mui/material/ListItemIcon'; import Checkbox from '@mui/material/Checkbox'; import Button from '@mui/material/Button'; import Divider from '@mui/material/Divider'; function not(a, b) { return a.filter((value) => b.indexOf(value) === -1); } function intersection(a, b) { return a.filter((value) => b.indexOf(value) !== -1); } function union(a, b) { return [...a, ...not(b, a)]; } export default function SelectAllTransferList() { const [checked, setChecked] = React.useState([]); const [left, setLeft] = React.useState([0, 1, 2, 3]); const [right, setRight] = React.useState([4, 5, 6, 7]); const leftChecked = intersection(checked, left); const rightChecked = intersection(checked, right); const handleToggle = (value) => () => { const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } setChecked(newChecked); }; const numberOfChecked = (items) => intersection(checked, items).length; const handleToggleAll = (items) => () => { if (numberOfChecked(items) === items.length) { setChecked(not(checked, items)); } else { setChecked(union(checked, items)); } }; const handleCheckedRight = () => { setRight(right.concat(leftChecked)); setLeft(not(left, leftChecked)); setChecked(not(checked, leftChecked)); }; const handleCheckedLeft = () => { setLeft(left.concat(rightChecked)); setRight(not(right, rightChecked)); setChecked(not(checked, rightChecked)); }; const customList = (title, items) => ( <Card> <CardHeader sx={{ px: 2, py: 1 }} avatar={ <Checkbox onClick={handleToggleAll(items)} checked={numberOfChecked(items) === items.length && items.length !== 0} indeterminate={ numberOfChecked(items) !== items.length && numberOfChecked(items) !== 0 } disabled={items.length === 0} inputProps={{ 'aria-label': 'all items selected', }} /> } title={title} subheader={`${numberOfChecked(items)}/${items.length} selected`} /> <Divider /> <List sx={{ width: 200, height: 230, bgcolor: 'background.paper', overflow: 'auto', }} dense component="div" role="list" > {items.map((value) => { const labelId = `transfer-list-all-item-${value}-label`; return ( <ListItem key={value} role="listitem" button onClick={handleToggle(value)} > <ListItemIcon> <Checkbox checked={checked.indexOf(value) !== -1} tabIndex={-1} disableRipple inputProps={{ 'aria-labelledby': labelId, }} /> </ListItemIcon> <ListItemText id={labelId} primary={`List item ${value + 1}`} /> </ListItem> ); })} </List> </Card> ); return ( <Grid container spacing={2} justifyContent="center" alignItems="center"> <Grid item>{customList('Choices', left)}</Grid> <Grid item> <Grid container direction="column" alignItems="center"> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleCheckedRight} disabled={leftChecked.length === 0} aria-label="move selected right" > &gt; </Button> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleCheckedLeft} disabled={rightChecked.length === 0} aria-label="move selected left" > &lt; </Button> </Grid> </Grid> <Grid item>{customList('Chosen', right)}</Grid> </Grid> ); }
3,314
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transfer-list/SelectAllTransferList.tsx
import * as React from 'react'; import Grid from '@mui/material/Grid'; import List from '@mui/material/List'; import Card from '@mui/material/Card'; import CardHeader from '@mui/material/CardHeader'; import ListItem from '@mui/material/ListItem'; import ListItemText from '@mui/material/ListItemText'; import ListItemIcon from '@mui/material/ListItemIcon'; import Checkbox from '@mui/material/Checkbox'; import Button from '@mui/material/Button'; import Divider from '@mui/material/Divider'; function not(a: readonly number[], b: readonly number[]) { return a.filter((value) => b.indexOf(value) === -1); } function intersection(a: readonly number[], b: readonly number[]) { return a.filter((value) => b.indexOf(value) !== -1); } function union(a: readonly number[], b: readonly number[]) { return [...a, ...not(b, a)]; } export default function SelectAllTransferList() { const [checked, setChecked] = React.useState<readonly number[]>([]); const [left, setLeft] = React.useState<readonly number[]>([0, 1, 2, 3]); const [right, setRight] = React.useState<readonly number[]>([4, 5, 6, 7]); const leftChecked = intersection(checked, left); const rightChecked = intersection(checked, right); const handleToggle = (value: number) => () => { const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } setChecked(newChecked); }; const numberOfChecked = (items: readonly number[]) => intersection(checked, items).length; const handleToggleAll = (items: readonly number[]) => () => { if (numberOfChecked(items) === items.length) { setChecked(not(checked, items)); } else { setChecked(union(checked, items)); } }; const handleCheckedRight = () => { setRight(right.concat(leftChecked)); setLeft(not(left, leftChecked)); setChecked(not(checked, leftChecked)); }; const handleCheckedLeft = () => { setLeft(left.concat(rightChecked)); setRight(not(right, rightChecked)); setChecked(not(checked, rightChecked)); }; const customList = (title: React.ReactNode, items: readonly number[]) => ( <Card> <CardHeader sx={{ px: 2, py: 1 }} avatar={ <Checkbox onClick={handleToggleAll(items)} checked={numberOfChecked(items) === items.length && items.length !== 0} indeterminate={ numberOfChecked(items) !== items.length && numberOfChecked(items) !== 0 } disabled={items.length === 0} inputProps={{ 'aria-label': 'all items selected', }} /> } title={title} subheader={`${numberOfChecked(items)}/${items.length} selected`} /> <Divider /> <List sx={{ width: 200, height: 230, bgcolor: 'background.paper', overflow: 'auto', }} dense component="div" role="list" > {items.map((value: number) => { const labelId = `transfer-list-all-item-${value}-label`; return ( <ListItem key={value} role="listitem" button onClick={handleToggle(value)} > <ListItemIcon> <Checkbox checked={checked.indexOf(value) !== -1} tabIndex={-1} disableRipple inputProps={{ 'aria-labelledby': labelId, }} /> </ListItemIcon> <ListItemText id={labelId} primary={`List item ${value + 1}`} /> </ListItem> ); })} </List> </Card> ); return ( <Grid container spacing={2} justifyContent="center" alignItems="center"> <Grid item>{customList('Choices', left)}</Grid> <Grid item> <Grid container direction="column" alignItems="center"> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleCheckedRight} disabled={leftChecked.length === 0} aria-label="move selected right" > &gt; </Button> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleCheckedLeft} disabled={rightChecked.length === 0} aria-label="move selected left" > &lt; </Button> </Grid> </Grid> <Grid item>{customList('Chosen', right)}</Grid> </Grid> ); }
3,315
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transfer-list/TransferList.js
import * as React from 'react'; import Grid from '@mui/material/Grid'; import List from '@mui/material/List'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import Checkbox from '@mui/material/Checkbox'; import Button from '@mui/material/Button'; import Paper from '@mui/material/Paper'; function not(a, b) { return a.filter((value) => b.indexOf(value) === -1); } function intersection(a, b) { return a.filter((value) => b.indexOf(value) !== -1); } export default function TransferList() { const [checked, setChecked] = React.useState([]); const [left, setLeft] = React.useState([0, 1, 2, 3]); const [right, setRight] = React.useState([4, 5, 6, 7]); const leftChecked = intersection(checked, left); const rightChecked = intersection(checked, right); const handleToggle = (value) => () => { const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } setChecked(newChecked); }; const handleAllRight = () => { setRight(right.concat(left)); setLeft([]); }; const handleCheckedRight = () => { setRight(right.concat(leftChecked)); setLeft(not(left, leftChecked)); setChecked(not(checked, leftChecked)); }; const handleCheckedLeft = () => { setLeft(left.concat(rightChecked)); setRight(not(right, rightChecked)); setChecked(not(checked, rightChecked)); }; const handleAllLeft = () => { setLeft(left.concat(right)); setRight([]); }; const customList = (items) => ( <Paper sx={{ width: 200, height: 230, overflow: 'auto' }}> <List dense component="div" role="list"> {items.map((value) => { const labelId = `transfer-list-item-${value}-label`; return ( <ListItem key={value} role="listitem" button onClick={handleToggle(value)} > <ListItemIcon> <Checkbox checked={checked.indexOf(value) !== -1} tabIndex={-1} disableRipple inputProps={{ 'aria-labelledby': labelId, }} /> </ListItemIcon> <ListItemText id={labelId} primary={`List item ${value + 1}`} /> </ListItem> ); })} </List> </Paper> ); return ( <Grid container spacing={2} justifyContent="center" alignItems="center"> <Grid item>{customList(left)}</Grid> <Grid item> <Grid container direction="column" alignItems="center"> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleAllRight} disabled={left.length === 0} aria-label="move all right" > ≫ </Button> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleCheckedRight} disabled={leftChecked.length === 0} aria-label="move selected right" > &gt; </Button> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleCheckedLeft} disabled={rightChecked.length === 0} aria-label="move selected left" > &lt; </Button> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleAllLeft} disabled={right.length === 0} aria-label="move all left" > ≪ </Button> </Grid> </Grid> <Grid item>{customList(right)}</Grid> </Grid> ); }
3,316
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transfer-list/TransferList.tsx
import * as React from 'react'; import Grid from '@mui/material/Grid'; import List from '@mui/material/List'; import ListItem from '@mui/material/ListItem'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import Checkbox from '@mui/material/Checkbox'; import Button from '@mui/material/Button'; import Paper from '@mui/material/Paper'; function not(a: readonly number[], b: readonly number[]) { return a.filter((value) => b.indexOf(value) === -1); } function intersection(a: readonly number[], b: readonly number[]) { return a.filter((value) => b.indexOf(value) !== -1); } export default function TransferList() { const [checked, setChecked] = React.useState<readonly number[]>([]); const [left, setLeft] = React.useState<readonly number[]>([0, 1, 2, 3]); const [right, setRight] = React.useState<readonly number[]>([4, 5, 6, 7]); const leftChecked = intersection(checked, left); const rightChecked = intersection(checked, right); const handleToggle = (value: number) => () => { const currentIndex = checked.indexOf(value); const newChecked = [...checked]; if (currentIndex === -1) { newChecked.push(value); } else { newChecked.splice(currentIndex, 1); } setChecked(newChecked); }; const handleAllRight = () => { setRight(right.concat(left)); setLeft([]); }; const handleCheckedRight = () => { setRight(right.concat(leftChecked)); setLeft(not(left, leftChecked)); setChecked(not(checked, leftChecked)); }; const handleCheckedLeft = () => { setLeft(left.concat(rightChecked)); setRight(not(right, rightChecked)); setChecked(not(checked, rightChecked)); }; const handleAllLeft = () => { setLeft(left.concat(right)); setRight([]); }; const customList = (items: readonly number[]) => ( <Paper sx={{ width: 200, height: 230, overflow: 'auto' }}> <List dense component="div" role="list"> {items.map((value: number) => { const labelId = `transfer-list-item-${value}-label`; return ( <ListItem key={value} role="listitem" button onClick={handleToggle(value)} > <ListItemIcon> <Checkbox checked={checked.indexOf(value) !== -1} tabIndex={-1} disableRipple inputProps={{ 'aria-labelledby': labelId, }} /> </ListItemIcon> <ListItemText id={labelId} primary={`List item ${value + 1}`} /> </ListItem> ); })} </List> </Paper> ); return ( <Grid container spacing={2} justifyContent="center" alignItems="center"> <Grid item>{customList(left)}</Grid> <Grid item> <Grid container direction="column" alignItems="center"> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleAllRight} disabled={left.length === 0} aria-label="move all right" > ≫ </Button> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleCheckedRight} disabled={leftChecked.length === 0} aria-label="move selected right" > &gt; </Button> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleCheckedLeft} disabled={rightChecked.length === 0} aria-label="move selected left" > &lt; </Button> <Button sx={{ my: 0.5 }} variant="outlined" size="small" onClick={handleAllLeft} disabled={right.length === 0} aria-label="move all left" > ≪ </Button> </Grid> </Grid> <Grid item>{customList(right)}</Grid> </Grid> ); }
3,317
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transfer-list/transfer-list.md
--- productId: material-ui title: Transfer list React component components: List, ListItem, Checkbox, Switch githubLabel: 'component: transfer list' --- # Transfer List <p class="description">A Transfer List (or "shuttle") enables the user to move one or more list items between lists.</p> {{"component": "modules/components/ComponentLinkHeader.js"}} ## Basic transfer list For completeness, this example includes buttons for "move all", but not every transfer list needs these. {{"demo": "TransferList.js", "bg": true}} ## Enhanced transfer list This example exchanges the "move all" buttons for a "select all / select none" checkbox and adds a counter. {{"demo": "SelectAllTransferList.js", "bg": true}} ## Limitations The component comes with a couple of limitations: - It only works on desktop. If you have a limited amount of options to select, prefer the [Autocomplete](/material-ui/react-autocomplete/#multiple-values) component. If mobile support is important for you, have a look at [#27579](https://github.com/mui/material-ui/issues/27579). - There are no high-level components exported from npm. The demos are based on composition. If this is important for you, have a look at [#27579](https://github.com/mui/material-ui/issues/27579).
3,318
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleCollapse.js
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Collapse from '@mui/material/Collapse'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleCollapse() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 300 }}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ '& > :not(style)': { display: 'flex', justifyContent: 'space-around', height: 120, width: 250, }, }} > <div> <Collapse in={checked}>{icon}</Collapse> <Collapse in={checked} collapsedSize={40}> {icon} </Collapse> </div> <div> <Box sx={{ width: '50%' }}> <Collapse orientation="horizontal" in={checked}> {icon} </Collapse> </Box> <Box sx={{ width: '50%' }}> <Collapse orientation="horizontal" in={checked} collapsedSize={40}> {icon} </Collapse> </Box> </div> </Box> </Box> ); }
3,319
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleCollapse.tsx
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Collapse from '@mui/material/Collapse'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleCollapse() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 300 }}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ '& > :not(style)': { display: 'flex', justifyContent: 'space-around', height: 120, width: 250, }, }} > <div> <Collapse in={checked}>{icon}</Collapse> <Collapse in={checked} collapsedSize={40}> {icon} </Collapse> </div> <div> <Box sx={{ width: '50%' }}> <Collapse orientation="horizontal" in={checked}> {icon} </Collapse> </Box> <Box sx={{ width: '50%' }}> <Collapse orientation="horizontal" in={checked} collapsedSize={40}> {icon} </Collapse> </Box> </div> </Box> </Box> ); }
3,320
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleFade.js
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Fade from '@mui/material/Fade'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleFade() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 180 }}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ display: 'flex' }}> <Fade in={checked}>{icon}</Fade> </Box> </Box> ); }
3,321
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleFade.tsx
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Fade from '@mui/material/Fade'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleFade() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 180 }}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ display: 'flex' }}> <Fade in={checked}>{icon}</Fade> </Box> </Box> ); }
3,322
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleFade.tsx.preview
<FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ display: 'flex' }}> <Fade in={checked}>{icon}</Fade> </Box>
3,323
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleGrow.js
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Grow from '@mui/material/Grow'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleGrow() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 180 }}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ display: 'flex' }}> <Grow in={checked}>{icon}</Grow> {/* Conditionally applies the timeout prop to change the entry speed. */} <Grow in={checked} style={{ transformOrigin: '0 0 0' }} {...(checked ? { timeout: 1000 } : {})} > {icon} </Grow> </Box> </Box> ); }
3,324
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleGrow.tsx
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Grow from '@mui/material/Grow'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleGrow() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 180 }}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ display: 'flex' }}> <Grow in={checked}>{icon}</Grow> {/* Conditionally applies the timeout prop to change the entry speed. */} <Grow in={checked} style={{ transformOrigin: '0 0 0' }} {...(checked ? { timeout: 1000 } : {})} > {icon} </Grow> </Box> </Box> ); }
3,325
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleGrow.tsx.preview
<FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ display: 'flex' }}> <Grow in={checked}>{icon}</Grow> {/* Conditionally applies the timeout prop to change the entry speed. */} <Grow in={checked} style={{ transformOrigin: '0 0 0' }} {...(checked ? { timeout: 1000 } : {})} > {icon} </Grow> </Box>
3,326
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleSlide.js
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Slide from '@mui/material/Slide'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleSlide() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 180, width: 130, position: 'relative', zIndex: 1, }} > <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Slide direction="up" in={checked} mountOnEnter unmountOnExit> {icon} </Slide> </Box> ); }
3,327
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleSlide.tsx
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Slide from '@mui/material/Slide'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleSlide() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 180, width: 130, position: 'relative', zIndex: 1, }} > <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Slide direction="up" in={checked} mountOnEnter unmountOnExit> {icon} </Slide> </Box> ); }
3,328
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleSlide.tsx.preview
<FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Slide direction="up" in={checked} mountOnEnter unmountOnExit> {icon} </Slide>
3,329
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleZoom.js
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Zoom from '@mui/material/Zoom'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleZoom() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 180 }}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ display: 'flex' }}> <Zoom in={checked}>{icon}</Zoom> <Zoom in={checked} style={{ transitionDelay: checked ? '500ms' : '0ms' }}> {icon} </Zoom> </Box> </Box> ); }
3,330
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleZoom.tsx
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Zoom from '@mui/material/Zoom'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SimpleZoom() { const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ height: 180 }}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ display: 'flex' }}> <Zoom in={checked}>{icon}</Zoom> <Zoom in={checked} style={{ transitionDelay: checked ? '500ms' : '0ms' }}> {icon} </Zoom> </Box> </Box> ); }
3,331
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SimpleZoom.tsx.preview
<FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Box sx={{ display: 'flex' }}> <Zoom in={checked}>{icon}</Zoom> <Zoom in={checked} style={{ transitionDelay: checked ? '500ms' : '0ms' }}> {icon} </Zoom> </Box>
3,332
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SlideFromContainer.js
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Slide from '@mui/material/Slide'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SlideFromContainer() { const [checked, setChecked] = React.useState(false); const containerRef = React.useRef(null); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ width: 240, borderRadius: 2, border: '1px solid', borderColor: 'divider', backgroundColor: 'background.default', }} > <Box sx={{ p: 2, height: 200, overflow: 'hidden' }} ref={containerRef}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show from target" /> <Slide in={checked} container={containerRef.current}> {icon} </Slide> </Box> </Box> ); }
3,333
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SlideFromContainer.tsx
import * as React from 'react'; import Box from '@mui/material/Box'; import Switch from '@mui/material/Switch'; import Paper from '@mui/material/Paper'; import Slide from '@mui/material/Slide'; import FormControlLabel from '@mui/material/FormControlLabel'; const icon = ( <Paper sx={{ m: 1, width: 100, height: 100 }} elevation={4}> <svg> <Box component="polygon" points="0,100 50,00, 100,100" sx={{ fill: (theme) => theme.palette.common.white, stroke: (theme) => theme.palette.divider, strokeWidth: 1, }} /> </svg> </Paper> ); export default function SlideFromContainer() { const [checked, setChecked] = React.useState(false); const containerRef = React.useRef<HTMLElement>(null); const handleChange = () => { setChecked((prev) => !prev); }; return ( <Box sx={{ width: 240, borderRadius: 2, border: '1px solid', borderColor: 'divider', backgroundColor: 'background.default', }} > <Box sx={{ p: 2, height: 200, overflow: 'hidden' }} ref={containerRef}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show from target" /> <Slide in={checked} container={containerRef.current}> {icon} </Slide> </Box> </Box> ); }
3,334
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/SlideFromContainer.tsx.preview
<Box sx={{ p: 2, height: 200, overflow: 'hidden' }} ref={containerRef}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show from target" /> <Slide in={checked} container={containerRef.current}> {icon} </Slide> </Box>
3,335
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/TransitionGroupExample.js
import * as React from 'react'; import Button from '@mui/material/Button'; import Collapse from '@mui/material/Collapse'; import IconButton from '@mui/material/IconButton'; import List from '@mui/material/List'; import ListItem from '@mui/material/ListItem'; import ListItemText from '@mui/material/ListItemText'; import DeleteIcon from '@mui/icons-material/Delete'; import { TransitionGroup } from 'react-transition-group'; const FRUITS = [ '🍏 Apple', '🍌 Banana', '🍍 Pineapple', '🥥 Coconut', '🍉 Watermelon', ]; function renderItem({ item, handleRemoveFruit }) { return ( <ListItem secondaryAction={ <IconButton edge="end" aria-label="delete" title="Delete" onClick={() => handleRemoveFruit(item)} > <DeleteIcon /> </IconButton> } > <ListItemText primary={item} /> </ListItem> ); } export default function TransitionGroupExample() { const [fruitsInBasket, setFruitsInBasket] = React.useState(FRUITS.slice(0, 3)); const handleAddFruit = () => { const nextHiddenItem = FRUITS.find((i) => !fruitsInBasket.includes(i)); if (nextHiddenItem) { setFruitsInBasket((prev) => [nextHiddenItem, ...prev]); } }; const handleRemoveFruit = (item) => { setFruitsInBasket((prev) => [...prev.filter((i) => i !== item)]); }; const addFruitButton = ( <Button variant="contained" disabled={fruitsInBasket.length >= FRUITS.length} onClick={handleAddFruit} > Add fruit to basket </Button> ); return ( <div> {addFruitButton} <List sx={{ mt: 1 }}> <TransitionGroup> {fruitsInBasket.map((item) => ( <Collapse key={item}>{renderItem({ item, handleRemoveFruit })}</Collapse> ))} </TransitionGroup> </List> </div> ); }
3,336
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/TransitionGroupExample.tsx
import * as React from 'react'; import Button from '@mui/material/Button'; import Collapse from '@mui/material/Collapse'; import IconButton from '@mui/material/IconButton'; import List from '@mui/material/List'; import ListItem from '@mui/material/ListItem'; import ListItemText from '@mui/material/ListItemText'; import DeleteIcon from '@mui/icons-material/Delete'; import { TransitionGroup } from 'react-transition-group'; const FRUITS = [ '🍏 Apple', '🍌 Banana', '🍍 Pineapple', '🥥 Coconut', '🍉 Watermelon', ]; interface RenderItemOptions { item: string; handleRemoveFruit: (item: string) => void; } function renderItem({ item, handleRemoveFruit }: RenderItemOptions) { return ( <ListItem secondaryAction={ <IconButton edge="end" aria-label="delete" title="Delete" onClick={() => handleRemoveFruit(item)} > <DeleteIcon /> </IconButton> } > <ListItemText primary={item} /> </ListItem> ); } export default function TransitionGroupExample() { const [fruitsInBasket, setFruitsInBasket] = React.useState(FRUITS.slice(0, 3)); const handleAddFruit = () => { const nextHiddenItem = FRUITS.find((i) => !fruitsInBasket.includes(i)); if (nextHiddenItem) { setFruitsInBasket((prev) => [nextHiddenItem, ...prev]); } }; const handleRemoveFruit = (item: string) => { setFruitsInBasket((prev) => [...prev.filter((i) => i !== item)]); }; const addFruitButton = ( <Button variant="contained" disabled={fruitsInBasket.length >= FRUITS.length} onClick={handleAddFruit} > Add fruit to basket </Button> ); return ( <div> {addFruitButton} <List sx={{ mt: 1 }}> <TransitionGroup> {fruitsInBasket.map((item) => ( <Collapse key={item}>{renderItem({ item, handleRemoveFruit })}</Collapse> ))} </TransitionGroup> </List> </div> ); }
3,337
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/TransitionGroupExample.tsx.preview
{addFruitButton} <List sx={{ mt: 1 }}> <TransitionGroup> {fruitsInBasket.map((item) => ( <Collapse key={item}>{renderItem({ item, handleRemoveFruit })}</Collapse> ))} </TransitionGroup> </List>
3,338
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/transitions/transitions.md
--- productId: material-ui title: React Transition component components: Collapse, Fade, Grow, Slide, Zoom githubLabel: 'component: transitions' --- # Transitions <p class="description">Transitions help to make a UI expressive and easy to use.</p> Material UI provides transitions that can be used to introduce some basic [motion](https://m2.material.io/design/motion/) to your applications. {{"component": "modules/components/ComponentLinkHeader.js", "design": false}} ## Collapse Expand from the start edge of the child element. Use the `orientation` prop if you need a horizontal collapse. The `collapsedSize` prop can be used to set the minimum width/height when not expanded. {{"demo": "SimpleCollapse.js", "bg": true}} ## Fade Fade in from transparent to opaque. {{"demo": "SimpleFade.js", "bg": true}} ## Grow Expands outwards from the center of the child element, while also fading in from transparent to opaque. The second example demonstrates how to change the `transform-origin`, and conditionally applies the `timeout` prop to change the entry speed. {{"demo": "SimpleGrow.js", "bg": true}} ## Slide Slide in from the edge of the screen. The `direction` prop controls which edge of the screen the transition starts from. The Transition component's `mountOnEnter` prop prevents the child component from being mounted until `in` is `true`. This prevents the relatively positioned component from scrolling into view from its off-screen position. Similarly, the `unmountOnExit` prop removes the component from the DOM after it has been transition off-screen. {{"demo": "SimpleSlide.js", "bg": true}} ### Slide relative to a container The Slide component also accepts `container` prop, which is a reference to a DOM node. If this prop is set, the Slide component will slide from the edge of that DOM node. {{"demo": "SlideFromContainer.js", "bg": true}} ## Zoom Expand outwards from the center of the child element. This example also demonstrates how to delay the enter transition. {{"demo": "SimpleZoom.js", "bg": true}} ## Child requirement - **Forward the style**: To better support server rendering, Material UI provides a `style` prop to the children of some transition components (Fade, Grow, Zoom, Slide). The `style` prop must be applied to the DOM for the animation to work as expected. - **Forward the ref**: The transition components require the first child element to forward its ref to the DOM node. For more details about ref, check out [Caveat with refs](/material-ui/guides/composition/#caveat-with-refs) - **Single element**: The transition components require only one child element (`React.Fragment` is not allowed). ```jsx // The `props` object contains a `style` prop. // You need to provide it to the `div` element as shown here. const MyComponent = React.forwardRef(function (props, ref) { return ( <div ref={ref} {...props}> Fade </div> ); }); export default function Main() { return ( <Fade> {/* MyComponent must be the only child */} <MyComponent /> </Fade> ); } ``` ## TransitionGroup To animate a component when it is mounted or unmounted, you can use the [`TransitionGroup`](http://reactcommunity.org/react-transition-group/transition-group/) component from _react-transition-group_. As components are added or removed, the `in` prop is toggled automatically by `TransitionGroup`. {{"demo": "TransitionGroupExample.js"}} ## TransitionComponent prop Some Material UI components use these transitions internally. These accept a `TransitionComponent` prop to customize the default transition. You can use any of the above components or your own. It should respect the following conditions: - Accepts an `in` prop. This corresponds to the open/close state. - Call the `onEnter` callback prop when the enter transition starts. - Call the `onExited` callback prop when the exit transition is completed. These two callbacks allow to unmount the children when in a closed state and fully transitioned. For more information on creating a custom transition, visit the _react-transition-group_ [`Transition` documentation](http://reactcommunity.org/react-transition-group/transition/). You can also visit the dedicated sections of some of the components: - [Modal](/material-ui/react-modal/#transitions) - [Dialog](/material-ui/react-dialog/#transitions) - [Popper](/material-ui/react-popper/#transitions) - [Snackbar](/material-ui/react-snackbar/#transitions) - [Tooltip](/material-ui/react-tooltip/#transitions) ## Performance & SEO The content of transition component is mounted by default even if `in={false}`. This default behavior has server-side rendering and SEO in mind. If you render expensive component trees inside your transition it might be a good idea to change this default behavior by enabling the `unmountOnExit` prop: ```jsx <Fade in={false} unmountOnExit /> ``` As with any performance optimization this is not a silver bullet. Be sure to identify bottlenecks first and then try out these optimization strategies.
3,339
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/typography/Types.js
import * as React from 'react'; import Box from '@mui/material/Box'; import Typography from '@mui/material/Typography'; export default function Types() { return ( <Box sx={{ width: '100%', maxWidth: 500 }}> <Typography variant="h1" gutterBottom> h1. Heading </Typography> <Typography variant="h2" gutterBottom> h2. Heading </Typography> <Typography variant="h3" gutterBottom> h3. Heading </Typography> <Typography variant="h4" gutterBottom> h4. Heading </Typography> <Typography variant="h5" gutterBottom> h5. Heading </Typography> <Typography variant="h6" gutterBottom> h6. Heading </Typography> <Typography variant="subtitle1" gutterBottom> subtitle1. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos blanditiis tenetur </Typography> <Typography variant="subtitle2" gutterBottom> subtitle2. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos blanditiis tenetur </Typography> <Typography variant="body1" gutterBottom> body1. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos blanditiis tenetur unde suscipit, quam beatae rerum inventore consectetur, neque doloribus, cupiditate numquam dignissimos laborum fugiat deleniti? Eum quasi quidem quibusdam. </Typography> <Typography variant="body2" gutterBottom> body2. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos blanditiis tenetur unde suscipit, quam beatae rerum inventore consectetur, neque doloribus, cupiditate numquam dignissimos laborum fugiat deleniti? Eum quasi quidem quibusdam. </Typography> <Typography variant="button" display="block" gutterBottom> button text </Typography> <Typography variant="caption" display="block" gutterBottom> caption text </Typography> <Typography variant="overline" display="block" gutterBottom> overline text </Typography> </Box> ); }
3,340
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/typography/Types.tsx
import * as React from 'react'; import Box from '@mui/material/Box'; import Typography from '@mui/material/Typography'; export default function Types() { return ( <Box sx={{ width: '100%', maxWidth: 500 }}> <Typography variant="h1" gutterBottom> h1. Heading </Typography> <Typography variant="h2" gutterBottom> h2. Heading </Typography> <Typography variant="h3" gutterBottom> h3. Heading </Typography> <Typography variant="h4" gutterBottom> h4. Heading </Typography> <Typography variant="h5" gutterBottom> h5. Heading </Typography> <Typography variant="h6" gutterBottom> h6. Heading </Typography> <Typography variant="subtitle1" gutterBottom> subtitle1. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos blanditiis tenetur </Typography> <Typography variant="subtitle2" gutterBottom> subtitle2. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos blanditiis tenetur </Typography> <Typography variant="body1" gutterBottom> body1. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos blanditiis tenetur unde suscipit, quam beatae rerum inventore consectetur, neque doloribus, cupiditate numquam dignissimos laborum fugiat deleniti? Eum quasi quidem quibusdam. </Typography> <Typography variant="body2" gutterBottom> body2. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos blanditiis tenetur unde suscipit, quam beatae rerum inventore consectetur, neque doloribus, cupiditate numquam dignissimos laborum fugiat deleniti? Eum quasi quidem quibusdam. </Typography> <Typography variant="button" display="block" gutterBottom> button text </Typography> <Typography variant="caption" display="block" gutterBottom> caption text </Typography> <Typography variant="overline" display="block" gutterBottom> overline text </Typography> </Box> ); }
3,341
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/typography/TypographyTheme.js
import * as React from 'react'; import { styled } from '@mui/material/styles'; const Div = styled('div')(({ theme }) => ({ ...theme.typography.button, backgroundColor: theme.palette.background.paper, padding: theme.spacing(1), })); export default function TypographyTheme() { return <Div>{"This div's text looks like that of a button."}</Div>; }
3,342
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/typography/TypographyTheme.tsx
import * as React from 'react'; import { styled } from '@mui/material/styles'; const Div = styled('div')(({ theme }) => ({ ...theme.typography.button, backgroundColor: theme.palette.background.paper, padding: theme.spacing(1), })); export default function TypographyTheme() { return <Div>{"This div's text looks like that of a button."}</Div>; }
3,343
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/typography/TypographyTheme.tsx.preview
<Div>{"This div's text looks like that of a button."}</Div>
3,344
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/typography/typography.md
--- productId: material-ui title: React Typography component components: Typography githubLabel: 'component: Typography' materialDesign: https://m2.material.io/design/typography/the-type-system.html --- # Typography <p class="description">Use typography to present your design and content as clearly and efficiently as possible.</p> {{"component": "modules/components/ComponentLinkHeader.js"}} ## Roboto font Material UI uses the [Roboto](https://fonts.google.com/specimen/Roboto) font by default. Add it to your project via Fontsource, or with the Google Fonts CDN. <codeblock storageKey="package-manager"> ```bash npm npm install @fontsource/roboto ``` ```bash yarn yarn add @fontsource/roboto ``` ```bash pnpm pnpm add @fontsource/roboto ``` </codeblock> Then you can import it in your entry point like this: ```tsx import '@fontsource/roboto/300.css'; import '@fontsource/roboto/400.css'; import '@fontsource/roboto/500.css'; import '@fontsource/roboto/700.css'; ``` :::info Fontsource can be configured to load specific subsets, weights, and styles. Material UI's default typography configuration relies only on the 300, 400, 500, and 700 font weights. ::: ### Google Web Fonts To install Roboto through the Google Web Fonts CDN, add the following code inside your project's <head /> tag: ```html <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;600;700&display=swap" /> ``` ## Component ### Usage The Typography component follows the [Material Design typographic scale](https://m2.material.io/design/typography/#type-scale) that provides a limited set of type sizes that work well together for a consistent layout. {{"demo": "Types.js"}} ### Theme keys In some situations you might not be able to use the Typography component. Hopefully, you might be able to take advantage of the [`typography`](/material-ui/customization/default-theme/?expand-path=$.typography) keys of the theme. {{"demo": "TypographyTheme.js"}} ## Customization ### Adding & disabling variants In addition to using the default typography variants, you can add custom ones, or disable any you don't need. See the [Adding & disabling variants](/material-ui/customization/typography/#adding-amp-disabling-variants) page for more info. ### Changing the semantic element The Typography component uses the `variantMapping` prop to associate a UI variant with a semantic element. It's important to realize that the style of a typography component is independent from the semantic underlying element. To change the underlying element for a one-off situation, like avoiding two `h1` elements in your page, use the `component` prop: ```jsx <Typography variant="h1" component="h2"> h1. Heading </Typography> ``` To change the typography element mapping globally, [use the theme](/material-ui/customization/typography/#adding-amp-disabling-variants): ```js const theme = createTheme({ components: { MuiTypography: { defaultProps: { variantMapping: { h1: 'h2', h2: 'h2', h3: 'h2', h4: 'h2', h5: 'h2', h6: 'h2', subtitle1: 'h2', subtitle2: 'h2', body1: 'span', body2: 'span', }, }, }, }, }); ``` ### System props As a CSS utility component, the Typography component supports all [`system`](/system/properties/) properties. You can use them as prop directly on the component. For example, here's how you'd add a margin-top: ```jsx <Typography mt={2}> ``` ## Accessibility Key factors to follow for an accessible typography: - **Color**. Provide enough contrast between text and its background, check out the minimum recommended [WCAG 2.0 color contrast ratio](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html) (4.5:1). - **Font size**. Use [relative units (rem)](/material-ui/customization/typography/#font-size), instead of pixels, to accommodate the user's browser settings. - **Heading hierarchy**. Based on [the W3 guidelines](https://www.w3.org/WAI/tutorials/page-structure/headings/), don't skip heading levels. Make sure to [separate the semantics from the style](#changing-the-semantic-element).
3,345
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/JavaScriptMedia.js
import * as React from 'react'; import json2mq from 'json2mq'; import useMediaQuery from '@mui/material/useMediaQuery'; export default function JavaScriptMedia() { const matches = useMediaQuery( json2mq({ minWidth: 600, }), ); return <span>{`{ minWidth: 600 } matches: ${matches}`}</span>; }
3,346
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/JavaScriptMedia.tsx
import * as React from 'react'; import json2mq from 'json2mq'; import useMediaQuery from '@mui/material/useMediaQuery'; export default function JavaScriptMedia() { const matches = useMediaQuery( json2mq({ minWidth: 600, }), ); return <span>{`{ minWidth: 600 } matches: ${matches}`}</span>; }
3,347
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/JavaScriptMedia.tsx.preview
<span>{`{ minWidth: 600 } matches: ${matches}`}</span>
3,348
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/ServerSide.js
import * as React from 'react'; import mediaQuery from 'css-mediaquery'; import { ThemeProvider } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; function MyComponent() { const matches = useMediaQuery('(min-width:600px)'); return <span>{`(min-width:600px) matches: ${matches}`}</span>; } export default function ServerSide() { const ssrMatchMedia = (query) => ({ matches: mediaQuery.match(query, { // The estimated CSS width of the browser. width: 800, }), }); return ( <ThemeProvider theme={{ components: { MuiUseMediaQuery: { // Change the default options of useMediaQuery defaultProps: { ssrMatchMedia }, }, }, }} > <MyComponent /> </ThemeProvider> ); }
3,349
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/ServerSide.tsx
import * as React from 'react'; import mediaQuery from 'css-mediaquery'; import { ThemeProvider, Theme } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; function MyComponent() { const matches = useMediaQuery('(min-width:600px)'); return <span>{`(min-width:600px) matches: ${matches}`}</span>; } export default function ServerSide() { const ssrMatchMedia = (query: string) => ({ matches: mediaQuery.match(query, { // The estimated CSS width of the browser. width: 800, }), }); return ( <ThemeProvider<Theme> theme={{ components: { MuiUseMediaQuery: { // Change the default options of useMediaQuery defaultProps: { ssrMatchMedia }, }, }, }} > <MyComponent /> </ThemeProvider> ); }
3,350
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/ServerSide.tsx.preview
<ThemeProvider<Theme> theme={{ components: { MuiUseMediaQuery: { // Change the default options of useMediaQuery defaultProps: { ssrMatchMedia }, }, }, }} > <MyComponent /> </ThemeProvider>
3,351
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/SimpleMediaQuery.js
import * as React from 'react'; import useMediaQuery from '@mui/material/useMediaQuery'; export default function SimpleMediaQuery() { const matches = useMediaQuery('(min-width:600px)'); return <span>{`(min-width:600px) matches: ${matches}`}</span>; }
3,352
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/SimpleMediaQuery.tsx
import * as React from 'react'; import useMediaQuery from '@mui/material/useMediaQuery'; export default function SimpleMediaQuery() { const matches = useMediaQuery('(min-width:600px)'); return <span>{`(min-width:600px) matches: ${matches}`}</span>; }
3,353
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/SimpleMediaQuery.tsx.preview
<span>{`(min-width:600px) matches: ${matches}`}</span>
3,354
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/ThemeHelper.js
import * as React from 'react'; import { createTheme, ThemeProvider, useTheme } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; function MyComponent() { const theme = useTheme(); const matches = useMediaQuery(theme.breakpoints.up('sm')); return <span>{`theme.breakpoints.up('sm') matches: ${matches}`}</span>; } const theme = createTheme(); export default function ThemeHelper() { return ( <ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider> ); }
3,355
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/ThemeHelper.tsx
import * as React from 'react'; import { createTheme, ThemeProvider, useTheme } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; function MyComponent() { const theme = useTheme(); const matches = useMediaQuery(theme.breakpoints.up('sm')); return <span>{`theme.breakpoints.up('sm') matches: ${matches}`}</span>; } const theme = createTheme(); export default function ThemeHelper() { return ( <ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider> ); }
3,356
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/ThemeHelper.tsx.preview
<ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider>
3,357
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/UseWidth.js
import * as React from 'react'; import { ThemeProvider, useTheme, createTheme } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; /** * Be careful using this hook. It only works because the number of * breakpoints in theme is static. It will break once you change the number of * breakpoints. See https://legacy.reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level */ function useWidth() { const theme = useTheme(); const keys = [...theme.breakpoints.keys].reverse(); return ( keys.reduce((output, key) => { // eslint-disable-next-line react-hooks/rules-of-hooks const matches = useMediaQuery(theme.breakpoints.up(key)); return !output && matches ? key : output; }, null) || 'xs' ); } function MyComponent() { const width = useWidth(); return <span>{`width: ${width}`}</span>; } const theme = createTheme(); export default function UseWidth() { return ( <ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider> ); }
3,358
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/UseWidth.tsx
import * as React from 'react'; import { Breakpoint, Theme, ThemeProvider, useTheme, createTheme, } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; type BreakpointOrNull = Breakpoint | null; /** * Be careful using this hook. It only works because the number of * breakpoints in theme is static. It will break once you change the number of * breakpoints. See https://legacy.reactjs.org/docs/hooks-rules.html#only-call-hooks-at-the-top-level */ function useWidth() { const theme: Theme = useTheme(); const keys: readonly Breakpoint[] = [...theme.breakpoints.keys].reverse(); return ( keys.reduce((output: BreakpointOrNull, key: Breakpoint) => { // eslint-disable-next-line react-hooks/rules-of-hooks const matches = useMediaQuery(theme.breakpoints.up(key)); return !output && matches ? key : output; }, null) || 'xs' ); } function MyComponent() { const width = useWidth(); return <span>{`width: ${width}`}</span>; } const theme = createTheme(); export default function UseWidth() { return ( <ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider> ); }
3,359
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/UseWidth.tsx.preview
<ThemeProvider theme={theme}> <MyComponent /> </ThemeProvider>
3,360
0
petrpan-code/mui/material-ui/docs/data/material/components
petrpan-code/mui/material-ui/docs/data/material/components/use-media-query/use-media-query.md
--- productId: material-ui title: Media queries in React for responsive design githubLabel: 'hook: useMediaQuery' --- # useMediaQuery <p class="description">This React hook listens for matches to a CSS media query. It allows the rendering of components based on whether the query matches or not.</p> Some of the key features: - ⚛️ It has an idiomatic React API. - 🚀 It's performant, it observes the document to detect when its media queries change, instead of polling the values periodically. - 📦 [1 kB gzipped](/size-snapshot/). - 🤖 It supports server-side rendering. {{"component": "modules/components/ComponentLinkHeader.js", "design": false}} ## Basic media query You should provide a media query to the first argument of the hook. The media query string can be any valid CSS media query, e.g. [`'(prefers-color-scheme: dark)'`](/material-ui/customization/dark-mode/#system-preference). {{"demo": "SimpleMediaQuery.js", "defaultCodeOpen": true}} ⚠️ You can't use `'print'` per browsers limitation, e.g. [Firefox](https://bugzilla.mozilla.org/show_bug.cgi?id=774398). ## Using Material UI's breakpoint helpers You can use Material UI's [breakpoint helpers](/material-ui/customization/breakpoints/) as follows: ```jsx import { useTheme } from '@mui/material/styles'; import useMediaQuery from '@mui/material/useMediaQuery'; function MyComponent() { const theme = useTheme(); const matches = useMediaQuery(theme.breakpoints.up('sm')); return <span>{`theme.breakpoints.up('sm') matches: ${matches}`}</span>; } ``` {{"demo": "ThemeHelper.js", "defaultCodeOpen": false}} Alternatively, you can use a callback function, accepting the theme as a first argument: ```jsx import useMediaQuery from '@mui/material/useMediaQuery'; function MyComponent() { const matches = useMediaQuery((theme) => theme.breakpoints.up('sm')); return <span>{`theme.breakpoints.up('sm') matches: ${matches}`}</span>; } ``` ⚠️ There is **no default** theme support, you have to inject it in a parent theme provider. ## Using JavaScript syntax You can use [json2mq](https://github.com/akiran/json2mq) to generate media query string from a JavaScript object. {{"demo": "JavaScriptMedia.js", "defaultCodeOpen": true}} ## Testing You need an implementation of [matchMedia](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) in your test environment. For instance, [jsdom doesn't support it yet](https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom). You should polyfill it. Using [css-mediaquery](https://github.com/ericf/css-mediaquery) to emulate it is recommended. ```js import mediaQuery from 'css-mediaquery'; function createMatchMedia(width) { return (query) => ({ matches: mediaQuery.match(query, { width, }), addListener: () => {}, removeListener: () => {}, }); } describe('MyTests', () => { beforeAll(() => { window.matchMedia = createMatchMedia(window.innerWidth); }); }); ``` ## Client-side only rendering To perform the server-side hydration, the hook needs to render twice. A first time with `defaultMatches`, the value of the server, and a second time with the resolved value. This double pass rendering cycle comes with a drawback: it's slower. You can set the `noSsr` option to `true` if you use the returned value **only** client-side. ```js const matches = useMediaQuery('(min-width:600px)', { noSsr: true }); ``` or it can turn it on globally with the theme: ```js const theme = createTheme({ components: { MuiUseMediaQuery: { defaultProps: { noSsr: true, }, }, }, }); ``` :::info Note that `noSsr` has no effects when using the `createRoot()` API (the client side only API introduced in React 18). ::: ## Server-side rendering :::warning Server-side rendering and client-side media queries are fundamentally at odds. Be aware of the tradeoff. The support can only be partial. ::: Try relying on client-side CSS media queries first. For instance, you could use: - [`<Box display>`](/system/display/#hiding-elements) - [`themes.breakpoints.up(x)`](/material-ui/customization/breakpoints/#css-media-queries) - or [`sx prop`](/system/getting-started/the-sx-prop/) If none of the above alternatives are an option, you can proceed reading this section of the documentation. First, you need to guess the characteristics of the client request, from the server. You have the choice between using: - **User agent**. Parse the user agent string of the client to extract information. Using [ua-parser-js](https://github.com/faisalman/ua-parser-js) to parse the user agent is recommended. - **Client hints**. Read the hints the client is sending to the server. Be aware that this feature is [not supported everywhere](https://caniuse.com/#search=client%20hint). Finally, you need to provide an implementation of [matchMedia](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) to the `useMediaQuery` with the previously guessed characteristics. Using [css-mediaquery](https://github.com/ericf/css-mediaquery) to emulate matchMedia is recommended. For instance on the server-side: ```js import * as ReactDOMServer from 'react-dom/server'; import parser from 'ua-parser-js'; import mediaQuery from 'css-mediaquery'; import { createTheme, ThemeProvider } from '@mui/material/styles'; function handleRender(req, res) { const deviceType = parser(req.headers['user-agent']).device.type || 'desktop'; const ssrMatchMedia = (query) => ({ matches: mediaQuery.match(query, { // The estimated CSS width of the browser. width: deviceType === 'mobile' ? '0px' : '1024px', }), }); const theme = createTheme({ components: { // Change the default options of useMediaQuery MuiUseMediaQuery: { defaultProps: { ssrMatchMedia, }, }, }, }); const html = ReactDOMServer.renderToString( <ThemeProvider theme={theme}> <App /> </ThemeProvider>, ); // … } ``` {{"demo": "ServerSide.js", "defaultCodeOpen": false}} Make sure you provide the same custom match media implementation to the client-side to guarantee a hydration match. ## Migrating from `withWidth()` The `withWidth()` higher-order component injects the screen width of the page. You can reproduce the same behavior with a `useWidth` hook: {{"demo": "UseWidth.js"}} ## API ### `useMediaQuery(query, [options]) => matches` #### Arguments 1. `query` (_string_ | _func_): A string representing the media query to handle or a callback function accepting the theme (in the context) that returns a string. 2. `options` (_object_ [optional]): - `options.defaultMatches` (_bool_ [optional]): As `window.matchMedia()` is unavailable on the server, it returns a default matches during the first mount. The default value is `false`. - `options.matchMedia` (_func_ [optional]): You can provide your own implementation of _matchMedia_. This can be used for handling an iframe content window. - `options.noSsr` (_bool_ [optional]): Defaults to `false`. To perform the server-side hydration, the hook needs to render twice. A first time with `defaultMatches`, the value of the server, and a second time with the resolved value. This double pass rendering cycle comes with a drawback: it's slower. You can set this option to `true` if you use the returned value **only** client-side. - `options.ssrMatchMedia` (_func_ [optional]): You can provide your own implementation of _matchMedia_, it's used when rendering server-side. Note: You can change the default options using the [`default props`](/material-ui/customization/theme-components/#theme-default-props) feature of the theme with the `MuiUseMediaQuery` key. #### Returns `matches`: Matches is `true` if the document currently matches the media query and `false` when it does not. #### Examples ```jsx import * as React from 'react'; import useMediaQuery from '@mui/material/useMediaQuery'; export default function SimpleMediaQuery() { const matches = useMediaQuery('(min-width:600px)'); return <span>{`(min-width:600px) matches: ${matches}`}</span>; } ```
3,361
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/breakpoints/MediaQuery.js
import * as React from 'react'; import { styled } from '@mui/material/styles'; import Typography from '@mui/material/Typography'; import { red, green, blue } from '@mui/material/colors'; const Root = styled('div')(({ theme }) => ({ padding: theme.spacing(1), [theme.breakpoints.down('md')]: { backgroundColor: red[500], }, [theme.breakpoints.up('md')]: { backgroundColor: blue[500], }, [theme.breakpoints.up('lg')]: { backgroundColor: green[500], }, })); export default function MediaQuery() { return ( <Root> <Typography>down(md): red</Typography> <Typography>up(md): blue</Typography> <Typography>up(lg): green</Typography> </Root> ); }
3,362
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/breakpoints/MediaQuery.tsx
import * as React from 'react'; import { styled } from '@mui/material/styles'; import Typography from '@mui/material/Typography'; import { red, green, blue } from '@mui/material/colors'; const Root = styled('div')(({ theme }) => ({ padding: theme.spacing(1), [theme.breakpoints.down('md')]: { backgroundColor: red[500], }, [theme.breakpoints.up('md')]: { backgroundColor: blue[500], }, [theme.breakpoints.up('lg')]: { backgroundColor: green[500], }, })); export default function MediaQuery() { return ( <Root> <Typography>down(md): red</Typography> <Typography>up(md): blue</Typography> <Typography>up(lg): green</Typography> </Root> ); }
3,363
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/breakpoints/MediaQuery.tsx.preview
<Root> <Typography>down(md): red</Typography> <Typography>up(md): blue</Typography> <Typography>up(lg): green</Typography> </Root>
3,364
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/breakpoints/breakpoints.md
# Breakpoints <p class="description">API that enables the use of breakpoints in a wide variety of contexts.</p> For optimal user experience, Material Design interfaces need to be able to adapt their layout at various breakpoints. Material UI uses a **simplified** implementation of the original [specification](https://m2.material.io/design/layout/responsive-layout-grid.html#breakpoints). The breakpoints are used internally in various components to make them responsive, but you can also take advantage of them for controlling the layout of your application through the [Grid](/material-ui/react-grid/) component. ## Default breakpoints Each breakpoint (a key) matches with a _fixed_ screen width (a value): <!-- Keep in sync with packages/mui-system/src/createTheme/createBreakpoints.d.ts --> - **xs,** extra-small: 0px - **sm,** small: 600px - **md,** medium: 900px - **lg,** large: 1200px - **xl,** extra-large: 1536px These values can be [customized](#custom-breakpoints). ## CSS Media Queries CSS media queries are the idiomatic approach to make your UI responsive. The theme provides five styles helpers to do so: - [theme.breakpoints.up(key)](#theme-breakpoints-up-key-media-query) - [theme.breakpoints.down(key)](#theme-breakpoints-down-key-media-query) - [theme.breakpoints.only(key)](#theme-breakpoints-only-key-media-query) - [theme.breakpoints.not(key)](#theme-breakpoints-not-key-media-query) - [theme.breakpoints.between(start, end)](#theme-breakpoints-between-start-end-media-query) In the following demo, we change the background color (red, blue & green) based on the screen width. ```jsx const styles = (theme) => ({ root: { padding: theme.spacing(1), [theme.breakpoints.down('md')]: { backgroundColor: theme.palette.secondary.main, }, [theme.breakpoints.up('md')]: { backgroundColor: theme.palette.primary.main, }, [theme.breakpoints.up('lg')]: { backgroundColor: green[500], }, }, }); ``` {{"demo": "MediaQuery.js"}} ## JavaScript Media Queries Sometimes, using CSS isn't enough. You might want to change the React rendering tree based on the breakpoint value, in JavaScript. ### useMediaQuery hook You can learn more on the [useMediaQuery](/material-ui/react-use-media-query/) page. ## Custom breakpoints You define your project's breakpoints in the `theme.breakpoints` section of your theme. <!-- Keep in sync with packages/mui-system/src/createTheme/createBreakpoints.d.ts --> - [`theme.breakpoints.values`](/material-ui/customization/default-theme/?expand-path=$.breakpoints.values): Default to the [above values](#default-breakpoints). The keys are your screen names, and the values are the min-width where that breakpoint should start. - `theme.breakpoints.unit`: Default to `'px'`. The unit used for the breakpoint's values. - `theme.breakpoints.step`: Default to `5`. The increment divided by 100 used to implement exclusive breakpoints. For example, `{ step: 5 }` means that `down(500)` will result in `'(max-width: 499.95px)'`. If you change the default breakpoints's values, you need to provide them all: ```jsx const theme = createTheme({ breakpoints: { values: { xs: 0, sm: 600, md: 900, lg: 1200, xl: 1536, }, }, }); ``` Feel free to have as few or as many breakpoints as you want, naming them in whatever way you'd prefer for your project. ```js const theme = createTheme({ breakpoints: { values: { mobile: 0, tablet: 640, laptop: 1024, desktop: 1200, }, }, }); ``` If you are using TypeScript, you would also need to use [module augmentation](/material-ui/guides/typescript/#customization-of-theme) for the theme to accept the above values. <!-- Tested with packages/mui-material/test/typescript/breakpointsOverrides.augmentation.tsconfig.json --> ```ts declare module '@mui/material/styles' { interface BreakpointOverrides { xs: false; // removes the `xs` breakpoint sm: false; md: false; lg: false; xl: false; mobile: true; // adds the `mobile` breakpoint tablet: true; laptop: true; desktop: true; } } ``` ## API ### `theme.breakpoints.up(key) => media query` <!-- Keep in sync with packages/mui-system/src/createTheme/createBreakpoints.d.ts --> #### Arguments 1. `key` (_string_ | _number_): A breakpoint key (`xs`, `sm`, etc.) or a screen width number in px. #### Returns `media query`: A media query string ready to be used with most styling solutions, which matches screen widths greater than the screen size given by the breakpoint key (inclusive). #### Examples ```js const styles = (theme) => ({ root: { backgroundColor: 'blue', // Match [md, ∞) // [900px, ∞) [theme.breakpoints.up('md')]: { backgroundColor: 'red', }, }, }); ``` ### `theme.breakpoints.down(key) => media query` <!-- Keep in sync with packages/mui-system/src/createTheme/createBreakpoints.d.ts --> #### Arguments 1. `key` (_string_ | _number_): A breakpoint key (`xs`, `sm`, etc.) or a screen width number in px. #### Returns `media query`: A media query string ready to be used with most styling solutions, which matches screen widths less than the screen size given by the breakpoint key (exclusive). #### Examples ```js const styles = (theme) => ({ root: { backgroundColor: 'blue', // Match [0, md) // [0, 900px) [theme.breakpoints.down('md')]: { backgroundColor: 'red', }, }, }); ``` ### `theme.breakpoints.only(key) => media query` <!-- Keep in sync with packages/mui-system/src/createTheme/createBreakpoints.d.ts --> #### Arguments 1. `key` (_string_): A breakpoint key (`xs`, `sm`, etc.). #### Returns `media query`: A media query string ready to be used with most styling solutions, which matches screen widths starting from the screen size given by the breakpoint key (inclusive) and stopping at the screen size given by the next breakpoint key (exclusive). #### Examples ```js const styles = (theme) => ({ root: { backgroundColor: 'blue', // Match [md, md + 1) // [md, lg) // [900px, 1200px) [theme.breakpoints.only('md')]: { backgroundColor: 'red', }, }, }); ``` ### `theme.breakpoints.not(key) => media query` <!-- Keep in sync with packages/mui-system/src/createTheme/createBreakpoints.d.ts --> #### Arguments 1. `key` (_string_): A breakpoint key (`xs`, `sm`, etc.). #### Returns `media query`: A media query string ready to be used with most styling solutions, which matches screen widths stopping at the screen size given by the breakpoint key (exclusive) and starting at the screen size given by the next breakpoint key (inclusive). #### Examples ```js const styles = (theme) => ({ root: { backgroundColor: 'blue', // Match [xs, md) and [md + 1, ∞) // [xs, md) and [lg, ∞) // [0px, 900px) and [1200px, ∞) [theme.breakpoints.not('md')]: { backgroundColor: 'red', }, }, }); ``` ### `theme.breakpoints.between(start, end) => media query` <!-- Keep in sync with packages/mui-system/src/createTheme/createBreakpoints.d.ts --> #### Arguments 1. `start` (_string_): A breakpoint key (`xs`, `sm`, etc.) or a screen width number in px. 2. `end` (_string_): A breakpoint key (`xs`, `sm`, etc.) or a screen width number in px. #### Returns `media query`: A media query string ready to be used with most styling solutions, which matches screen widths greater than the screen size given by the breakpoint key in the first argument (inclusive) and less than the screen size given by the breakpoint key in the second argument (exclusive). #### Examples ```js const styles = (theme) => ({ root: { backgroundColor: 'blue', // Match [sm, md) // [600px, 900px) [theme.breakpoints.between('sm', 'md')]: { backgroundColor: 'red', }, }, }); ``` ## Default values You can explore the default values of the breakpoints using [the theme explorer](/material-ui/customization/default-theme/?expand-path=$.breakpoints) or by opening the dev tools console on this page (`window.theme.breakpoints`).
3,365
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/color/Color.js
import * as React from 'react'; import Box from '@mui/material/Box'; import { styled, useTheme } from '@mui/material/styles'; import * as colors from '@mui/material/colors'; const mainColors = [ 'Red', 'Pink', 'Purple', 'Deep Purple', 'Indigo', 'Blue', 'Light Blue', 'Cyan', 'Teal', 'Green', 'Light Green', 'Lime', 'Yellow', 'Amber', 'Orange', 'Deep Orange', 'Brown', 'Grey', 'Blue Grey', ]; const mainPalette = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]; const altPalette = ['A100', 'A200', 'A400', 'A700']; const ColorGroup = styled('ul', { name: 'ColorGroup' })(({ theme }) => ({ padding: 0, margin: theme.spacing(0, 2, 2, 0), flexGrow: 1, [theme.breakpoints.up('sm')]: { flexGrow: 0, width: '30%', }, })); const ColorValue = styled('span', { name: 'ColorValue' })(({ theme }) => ({ ...theme.typography.caption, color: 'inherit', fontWeight: 'inherit', })); const ColorBlock = styled('li', { name: 'ColorBlock' })( ({ theme }) => theme.typography.body2, ); function getColorBlock(theme, colorName, colorValue, colorTitle) { const bgColor = colors[colorName][colorValue]; const fgColor = theme.palette.getContrastText(bgColor); let blockTitle; if (colorTitle) { blockTitle = <Box sx={{ mb: '60px' }}>{colorName}</Box>; } let rowStyle = { backgroundColor: bgColor, color: fgColor, listStyle: 'none', padding: 15, }; if (colorValue.toString().indexOf('A1') === 0) { rowStyle = { ...rowStyle, marginTop: 4, }; } return ( <ColorBlock style={rowStyle} key={colorValue}> {blockTitle} <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', }} > <span>{colorValue}</span> <ColorValue>{bgColor}</ColorValue> </Box> </ColorBlock> ); } function getColorGroup(options) { const { theme, color, showAltPalette } = options; const cssColor = color .replace(' ', '') .replace(color.charAt(0), color.charAt(0).toLowerCase()); let colorsList = []; colorsList = mainPalette.map((mainValue) => getColorBlock(theme, cssColor, mainValue), ); if (showAltPalette) { altPalette.forEach((altValue) => { colorsList.push(getColorBlock(theme, cssColor, altValue)); }); } return ( <ColorGroup key={cssColor}> {getColorBlock(theme, cssColor, 500, true)} <Box sx={{ height: 4, listStyle: 'none' }} component="li" role="separator" /> {colorsList} </ColorGroup> ); } function Color() { const theme = useTheme(); return ( <Box sx={{ display: 'flex', flexWrap: 'wrap' }}> {mainColors.map((mainColor) => getColorGroup({ theme, color: mainColor, showAltPalette: true, }), )} </Box> ); } export default Color;
3,366
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/color/ColorDemo.js
import * as React from 'react'; import PropTypes from 'prop-types'; import { useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import AppBar from '@mui/material/AppBar'; import Toolbar from '@mui/material/Toolbar'; import Fab from '@mui/material/Fab'; import IconButton from '@mui/material/IconButton'; import MenuIcon from '@mui/icons-material/Menu'; import Typography from '@mui/material/Typography'; import AddIcon from '@mui/icons-material/Add'; function ColorDemo(props) { const { data } = props; const theme = useTheme(); const primary = theme.palette.augmentColor({ color: { main: data.primary, output: data.primaryShade === 4 ? `${data.primaryHue}` : `{ main: '${data.primary}', }`, }, }); const secondary = theme.palette.augmentColor({ color: { main: data.secondary, output: data.secondaryShade === 11 ? `${data.secondaryHue}` : `{ main: '${data.secondary}', }`, }, }); return ( <Box sx={{ position: 'relative', overflow: 'hidden' }}> <Box sx={{ position: 'relative', height: 390, bgcolor: 'background.paper' }}> <Box sx={{ width: '100%', height: 24 }} style={{ backgroundColor: primary.dark }} /> <AppBar position="static" style={{ backgroundColor: primary.main }}> <Toolbar style={{ color: primary.contrastText }}> <IconButton edge="start" sx={{ mr: '20px' }} color="inherit" aria-label="menu" > <MenuIcon /> </IconButton> <Typography component="div" variant="h6" color="inherit"> Color </Typography> </Toolbar> </AppBar> <Box component="pre" sx={{ m: 2, fontSize: 16 }}> {`{ palette: { primary: ${primary.output}, secondary: ${secondary.output}, }, }`} </Box> <Fab sx={{ position: 'absolute', bottom: theme.spacing(2), right: theme.spacing(2), }} style={{ backgroundColor: secondary.main }} aria-label="add" > <AddIcon htmlColor={secondary.contrastText} /> </Fab> </Box> </Box> ); } ColorDemo.propTypes = { data: PropTypes.object.isRequired, }; export default ColorDemo;
3,367
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/color/ColorTool.js
import * as React from 'react'; import PropTypes from 'prop-types'; import { rgbToHex, useTheme } from '@mui/material/styles'; import * as colors from '@mui/material/colors'; import Box from '@mui/material/Box'; import Grid from '@mui/material/Grid'; import Input from '@mui/material/Input'; import Radio from '@mui/material/Radio'; import Tooltip from '@mui/material/Tooltip'; import Typography from '@mui/material/Typography'; import Button from '@mui/material/Button'; import CheckIcon from '@mui/icons-material/Check'; import Slider from '@mui/material/Slider'; import { capitalize } from '@mui/material/utils'; import { DispatchContext } from 'docs/src/modules/components/ThemeContext'; import ColorDemo from './ColorDemo'; const defaults = { primary: '#2196f3', secondary: '#f50057', }; const hues = [ 'red', 'pink', 'purple', 'deepPurple', 'indigo', 'blue', 'lightBlue', 'cyan', 'teal', 'green', 'lightGreen', 'lime', 'yellow', 'amber', 'orange', 'deepOrange', ]; const shades = [ 900, 800, 700, 600, 500, 400, 300, 200, 100, 50, 'A700', 'A400', 'A200', 'A100', ]; const TooltipRadio = React.forwardRef(function TooltipRadio(props, ref) { const { 'aria-labelledby': ariaLabelledBy, 'aria-label': ariaLabel, inputProps, ...other } = props; return ( <Radio ref={ref} {...other} inputProps={{ ...inputProps, 'aria-labelledby': ariaLabelledBy, 'aria-label': ariaLabel, }} /> ); }); TooltipRadio.propTypes = { // possibly opaque identifier 'aria-label': PropTypes.oneOfType([PropTypes.string, PropTypes.object]), 'aria-labelledby': PropTypes.oneOfType([PropTypes.string, PropTypes.object]), inputProps: PropTypes.object, }; function ColorTool() { const dispatch = React.useContext(DispatchContext); const theme = useTheme(); const [state, setState] = React.useState({ primary: defaults.primary, secondary: defaults.secondary, primaryInput: defaults.primary, secondaryInput: defaults.secondary, primaryHue: 'blue', secondaryHue: 'pink', primaryShade: 4, secondaryShade: 11, }); const handleChangeColor = (name) => (event) => { const isRgb = (string) => /rgb\([0-9]{1,3}\s*,\s*[0-9]{1,3}\s*,\s*[0-9]{1,3}\)/i.test(string); const isHex = (string) => /^#?([0-9a-f]{3})$|^#?([0-9a-f]){6}$/i.test(string); let { target: { value: color }, } = event; setState((prevState) => ({ ...prevState, [`${name}Input`]: color, })); let isValidColor = false; if (isRgb(color)) { isValidColor = true; } else if (isHex(color)) { isValidColor = true; if (color.indexOf('#') === -1) { color = `#${color}`; } } if (isValidColor) { setState((prevState) => ({ ...prevState, [name]: color, })); } }; const handleChangeHue = (name) => (event) => { const hue = event.target.value; const color = colors[hue][shades[state[`${name}Shade`]]]; setState({ ...state, [`${name}Hue`]: hue, [name]: color, [`${name}Input`]: color, }); }; const handleChangeShade = (name) => (event, shade) => { const color = colors[state[`${name}Hue`]][shades[shade]]; setState({ ...state, [`${name}Shade`]: shade, [name]: color, [`${name}Input`]: color, }); }; const handleChangeDocsColors = () => { const paletteColors = { primary: { ...colors[state.primaryHue], main: state.primary }, secondary: { ...colors[state.secondaryHue], main: state.secondary }, }; dispatch({ type: 'CHANGE', payload: { paletteColors }, }); document.cookie = `paletteColors=${JSON.stringify( paletteColors, )};path=/;max-age=31536000`; }; const handleResetDocsColors = () => { dispatch({ type: 'RESET_COLORS' }); document.cookie = 'paletteColors=;path=/;max-age=0'; }; const colorBar = (color) => { const background = theme.palette.augmentColor({ color: { main: color, }, }); return ( <Grid container sx={{ mt: 2 }}> {['dark', 'main', 'light'].map((key) => ( <Box sx={{ width: 64, height: 64, display: 'flex', justifyContent: 'center', alignItems: 'center', }} style={{ backgroundColor: background[key] }} key={key} > <Typography variant="caption" style={{ color: theme.palette.getContrastText(background[key]), }} > {rgbToHex(background[key])} </Typography> </Box> ))} </Grid> ); }; const colorPicker = (intent) => { const intentInput = state[`${intent}Input`]; const intentShade = state[`${intent}Shade`]; const color = state[`${intent}`]; return ( <Grid item xs={12} sm={6} md={4}> <Typography component="label" gutterBottom htmlFor={intent} variant="h6"> {capitalize(intent)} </Typography> <Input id={intent} value={intentInput} onChange={handleChangeColor(intent)} fullWidth /> <Box sx={{ display: 'flex', alignItems: 'center', mt: 2, mb: 2 }}> <Typography id={`${intent}ShadeSliderLabel`}>Shade:</Typography> <Slider sx={{ width: 'calc(100% - 80px)', ml: 3, mr: 3 }} value={intentShade} min={0} max={13} step={1} onChange={handleChangeShade(intent)} aria-labelledby={`${intent}ShadeSliderLabel`} /> <Typography>{shades[intentShade]}</Typography> </Box> <Box sx={{ width: 192 }}> {hues.map((hue) => { const shade = intent === 'primary' ? shades[state.primaryShade] : shades[state.secondaryShade]; const backgroundColor = colors[hue][shade]; return ( <Tooltip placement="right" title={hue} key={hue}> <TooltipRadio sx={{ p: 0 }} color="default" checked={state[intent] === backgroundColor} onChange={handleChangeHue(intent)} value={hue} name={intent} icon={ <Box sx={{ width: 48, height: 48 }} style={{ backgroundColor }} /> } checkedIcon={ <Box sx={{ width: 48, height: 48, border: 1, borderColor: 'white', color: 'common.white', display: 'flex', justifyContent: 'center', alignItems: 'center', }} style={{ backgroundColor }} > <CheckIcon style={{ fontSize: 30 }} /> </Box> } /> </Tooltip> ); })} </Box> {colorBar(color)} </Grid> ); }; return ( <Grid container spacing={5} sx={{ p: 0 }}> {colorPicker('primary')} {colorPicker('secondary')} <Grid item xs={12} sm={6} md={4}> <ColorDemo data={state} /> </Grid> <Grid item xs={12}> <Button variant="contained" onClick={handleChangeDocsColors}> Set Docs Colors </Button> <Button variant="outlined" onClick={handleResetDocsColors} sx={{ ml: 1 }}> Reset Docs Colors </Button> </Grid> </Grid> ); } export default ColorTool;
3,368
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/color/color.md
# Color <p class="description">Convey meaning through color. Out of the box you get access to all colors in the Material Design guidelines.</p> The Material Design [color system](https://m2.material.io/design/color/) can be used to create a color theme that reflects your brand or style. ## Picking colors ### Official color tool The Material Design team has also built an awesome palette configuration tool: [material.io/resources/color/](https://m2.material.io/inline-tools/color/). This can help you create a color palette for your UI, as well as measure the accessibility level of any color combination. <a href="https://m2.material.io/inline-tools/color/" target="_blank" rel="noopener nofollow"> <img src="/static/images/color/colorTool.png" alt="Official color tool" style="width: 574px" width=1148" height="610" /> </a> <br /> <br /> The output can be fed into `createTheme()` function: ```js import { createTheme } from '@mui/material/styles'; const theme = createTheme({ palette: { primary: { light: '#757ce8', main: '#3f50b5', dark: '#002884', contrastText: '#fff', }, secondary: { light: '#ff7961', main: '#f44336', dark: '#ba000d', contrastText: '#000', }, }, }); ``` ### Playground To test a [material.io/design/color](https://m2.material.io/design/color/) color scheme with the MUI documentation, simply select colors using the palette and sliders below. Alternatively, you can enter hex values in the Primary and Secondary text fields. {{"demo": "ColorTool.js", "hideToolbar": true, "bg": true}} The output shown in the color sample can be pasted directly into a [`createTheme()`](/material-ui/customization/theming/#createtheme-options-args-theme) function (to be used with [`ThemeProvider`](/material-ui/customization/theming/#theme-provider)): ```jsx import { createTheme } from '@mui/material/styles'; import { purple } from '@mui/material/colors'; const theme = createTheme({ palette: { primary: { main: purple[500], }, secondary: { main: '#f44336', }, }, }); ``` Only the `main` shades need to be provided (unless you wish to further customize `light`, `dark` or `contrastText`), as the other colors will be calculated by `createTheme()`, as described in the [Theme customization](/material-ui/customization/palette/) section. If you are using the default primary and / or secondary shades then by providing the color object, `createTheme()` will use the appropriate shades from the material color for main, light and dark. ### Tools by the community - [mui-theme-creator](https://zenoo.github.io/mui-theme-creator/): A tool to help design and customize themes for the Material UI component library. Includes basic site templates to show various components and how they are affected by the theme - [Material palette generator](https://m2.material.io/inline-tools/color/): The Material palette generator can be used to generate a palette for any color you input. ## 2014 Material Design color palettes These color palettes, originally created by Material Design in 2014, are comprised of colors designed to work together harmoniously, and can be used to develop your brand palette. To generate your own harmonious palettes, use the palette generation tool. ### Important Terms - **Palette**: A palette is a collection of colors, i.e. hues and their shades. Material UI provides all colors from the Material Design guidelines. [This color palette](#color-palette) has been designed with colors that work harmoniously with each other. - **Hue & Shade**: A single color within the palette is made up of a hue such as "red", and shade, such as "500". "red 50" is the lightest shade of red (_pink!_), while "red 900" is the darkest. In addition, most hues come with "accent" shades, prefixed with an `A`. ### Color palette Given a _HUE_ (red, pink, etc.) and a _SHADE_ (500, 600, etc.) you can import the color like this: ```jsx import { red } from '@mui/material/colors'; const color = red[500]; ``` {{"demo": "Color.js", "hideToolbar": true, "bg": "inline"}} ### Examples For instance, you can refer to complementary primary and accent colors, "red 500" and "purple A200" like so: ```js import { purple, red } from '@mui/material/colors'; const primary = red[500]; // #f44336 const accent = purple['A200']; // #e040fb const accent = purple.A200; // #e040fb (alternative method) ``` ### Accessibility [WCAG 2.1 Rule 1.4.3](https://www.w3.org/WAI/WCAG21/Understanding/contrast-minimum.html) does recommend that you have a minimum of a 4.5:1 contrast ratio for the visual presentation of text and images of text. Material UI currently only enforces a 3:1 contrast ratio. If you would like to meet WCAG 2.1 AA compliance, you can increase your minimum contrast ratio as described in the [Theme customization](/material-ui/customization/palette/#accessibility) section.
3,369
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/dark-mode/DarkTheme.js
import * as React from 'react'; import Typography from '@mui/material/Typography'; import Grid from '@mui/material/Grid'; import Box from '@mui/material/Box'; import { styled, ThemeProvider, useTheme, createTheme } from '@mui/material/styles'; const Root = styled('div')(({ theme }) => ({ backgroundColor: theme.palette.background.default, color: theme.palette.text.primary, padding: theme.spacing(2), borderRadius: 4, [theme.breakpoints.up('md')]: { padding: theme.spacing(3), }, })); const Color = styled(Grid)(({ theme }) => ({ display: 'flex', alignItems: 'center', '& div:first-of-type': { width: theme.spacing(5), height: theme.spacing(5), flexShrink: 0, marginRight: theme.spacing(1.5), borderRadius: theme.shape.borderRadius, }, })); function Demo() { const theme = useTheme(); const item = (color, name, expanded = false, border = false) => ( <Color item xs={12} sm={6} md={expanded ? 8 : 4}> <div style={{ backgroundColor: color, border: border ? `1px solid ${theme.palette.divider}` : undefined, }} /> <div> <Typography variant="body2">{name}</Typography> <Typography variant="body2" color="text.secondary"> {color} </Typography> </div> </Color> ); return ( <Root> <Typography gutterBottom sx={{ mb: 1.5 }}> Typography </Typography> <Grid container spacing={1}> {item(theme.palette.text.primary, 'palette.text.primary')} {item(theme.palette.text.secondary, 'palette.text.secondary')} {item(theme.palette.text.disabled, 'palette.text.disabled')} </Grid> <Typography gutterBottom sx={{ mt: 4, mb: 1.5 }}> Buttons </Typography> <Grid container spacing={1}> {item(theme.palette.action.active, 'palette.action.active')} {item(theme.palette.action.hover, 'palette.action.hover')} {item(theme.palette.action.selected, 'palette.action.selected')} {item(theme.palette.action.disabled, 'palette.action.disabled')} {item( theme.palette.action.disabledBackground, 'palette.action.disabledBackground', true, )} </Grid> <Typography gutterBottom sx={{ mt: 4, mb: 1.5 }}> Background </Typography> <Grid container spacing={1}> {item( theme.palette.background.default, 'palette.background.default', false, true, )} {item( theme.palette.background.paper, 'palette.background.paper', false, true, )} </Grid> <Typography gutterBottom sx={{ mt: 4, mb: 1.5 }}> Divider </Typography> <Grid container spacing={1}> {item(theme.palette.divider, 'palette.divider')} </Grid> </Root> ); } const lightTheme = createTheme(); const darkTheme = createTheme({ palette: { // Switching the dark mode on is a single property value change. mode: 'dark', }, }); export default function DarkTheme() { // Note that if you intend to use two or more themes at the same time on your site, // you need to wrap them with a single ThemeProvider at the root (not like in this example). return ( <Box sx={{ width: '100%' }}> <ThemeProvider theme={darkTheme}> <Demo /> </ThemeProvider> <ThemeProvider theme={lightTheme}> <Demo /> </ThemeProvider> </Box> ); }
3,370
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/dark-mode/DarkThemeWithCustomPalette.js
import * as React from 'react'; import Box from '@mui/material/Box'; import { ThemeProvider, useTheme, createTheme } from '@mui/material/styles'; import { amber, deepOrange, grey } from '@mui/material/colors'; const getDesignTokens = (mode) => ({ palette: { mode, primary: { ...amber, ...(mode === 'dark' && { main: amber[300], }), }, ...(mode === 'dark' && { background: { default: deepOrange[900], paper: deepOrange[900], }, }), text: { ...(mode === 'light' ? { primary: grey[900], secondary: grey[800], } : { primary: '#fff', secondary: grey[500], }), }, }, }); function MyApp() { const theme = useTheme(); return ( <Box sx={{ display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'center', bgcolor: 'background.default', color: 'text.primary', borderRadius: 1, p: 3, }} > This is a {theme.palette.mode} mode theme with custom palette </Box> ); } const darkModeTheme = createTheme(getDesignTokens('dark')); export default function DarkThemeWithCustomPalette() { return ( <ThemeProvider theme={darkModeTheme}> <MyApp /> </ThemeProvider> ); }
3,371
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/dark-mode/DarkThemeWithCustomPalette.tsx
import * as React from 'react'; import Box from '@mui/material/Box'; import { ThemeProvider, useTheme, createTheme } from '@mui/material/styles'; import { amber, deepOrange, grey } from '@mui/material/colors'; import { PaletteMode } from '@mui/material'; const getDesignTokens = (mode: PaletteMode) => ({ palette: { mode, primary: { ...amber, ...(mode === 'dark' && { main: amber[300], }), }, ...(mode === 'dark' && { background: { default: deepOrange[900], paper: deepOrange[900], }, }), text: { ...(mode === 'light' ? { primary: grey[900], secondary: grey[800], } : { primary: '#fff', secondary: grey[500], }), }, }, }); function MyApp() { const theme = useTheme(); return ( <Box sx={{ display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'center', bgcolor: 'background.default', color: 'text.primary', borderRadius: 1, p: 3, }} > This is a {theme.palette.mode} mode theme with custom palette </Box> ); } const darkModeTheme = createTheme(getDesignTokens('dark')); export default function DarkThemeWithCustomPalette() { return ( <ThemeProvider theme={darkModeTheme}> <MyApp /> </ThemeProvider> ); }
3,372
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/dark-mode/DarkThemeWithCustomPalette.tsx.preview
<ThemeProvider theme={darkModeTheme}> <MyApp /> </ThemeProvider>
3,373
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/dark-mode/ToggleColorMode.js
import * as React from 'react'; import IconButton from '@mui/material/IconButton'; import Box from '@mui/material/Box'; import { useTheme, ThemeProvider, createTheme } from '@mui/material/styles'; import Brightness4Icon from '@mui/icons-material/Brightness4'; import Brightness7Icon from '@mui/icons-material/Brightness7'; const ColorModeContext = React.createContext({ toggleColorMode: () => {} }); function MyApp() { const theme = useTheme(); const colorMode = React.useContext(ColorModeContext); return ( <Box sx={{ display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'center', bgcolor: 'background.default', color: 'text.primary', borderRadius: 1, p: 3, }} > {theme.palette.mode} mode <IconButton sx={{ ml: 1 }} onClick={colorMode.toggleColorMode} color="inherit"> {theme.palette.mode === 'dark' ? <Brightness7Icon /> : <Brightness4Icon />} </IconButton> </Box> ); } export default function ToggleColorMode() { const [mode, setMode] = React.useState('light'); const colorMode = React.useMemo( () => ({ toggleColorMode: () => { setMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light')); }, }), [], ); const theme = React.useMemo( () => createTheme({ palette: { mode, }, }), [mode], ); return ( <ColorModeContext.Provider value={colorMode}> <ThemeProvider theme={theme}> <MyApp /> </ThemeProvider> </ColorModeContext.Provider> ); }
3,374
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/dark-mode/ToggleColorMode.tsx
import * as React from 'react'; import IconButton from '@mui/material/IconButton'; import Box from '@mui/material/Box'; import { useTheme, ThemeProvider, createTheme } from '@mui/material/styles'; import Brightness4Icon from '@mui/icons-material/Brightness4'; import Brightness7Icon from '@mui/icons-material/Brightness7'; const ColorModeContext = React.createContext({ toggleColorMode: () => {} }); function MyApp() { const theme = useTheme(); const colorMode = React.useContext(ColorModeContext); return ( <Box sx={{ display: 'flex', width: '100%', alignItems: 'center', justifyContent: 'center', bgcolor: 'background.default', color: 'text.primary', borderRadius: 1, p: 3, }} > {theme.palette.mode} mode <IconButton sx={{ ml: 1 }} onClick={colorMode.toggleColorMode} color="inherit"> {theme.palette.mode === 'dark' ? <Brightness7Icon /> : <Brightness4Icon />} </IconButton> </Box> ); } export default function ToggleColorMode() { const [mode, setMode] = React.useState<'light' | 'dark'>('light'); const colorMode = React.useMemo( () => ({ toggleColorMode: () => { setMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light')); }, }), [], ); const theme = React.useMemo( () => createTheme({ palette: { mode, }, }), [mode], ); return ( <ColorModeContext.Provider value={colorMode}> <ThemeProvider theme={theme}> <MyApp /> </ThemeProvider> </ColorModeContext.Provider> ); }
3,375
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/dark-mode/ToggleColorMode.tsx.preview
<ColorModeContext.Provider value={colorMode}> <ThemeProvider theme={theme}> <MyApp /> </ThemeProvider> </ColorModeContext.Provider>
3,376
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/dark-mode/dark-mode.md
# Dark mode <p class="description">Material UI comes with two palette modes: light (the default) and dark.</p> ## Dark mode by default You can make your application use the dark theme as the default—regardless of the user's preference—by adding `mode: 'dark'` to the `createTheme` helper: ```js import { ThemeProvider, createTheme } from '@mui/material/styles'; import CssBaseline from '@mui/material/CssBaseline'; const darkTheme = createTheme({ palette: { mode: 'dark', }, }); export default function App() { return ( <ThemeProvider theme={darkTheme}> <CssBaseline /> <main>This app is using the dark mode</main> </ThemeProvider> ); } ``` Adding `mode: 'dark'` to the `createTheme` helper modifies several palette values, as shown in the following demo: {{"demo": "DarkTheme.js", "bg": "inline", "hideToolbar": true}} Adding `<CssBaseline />` inside of the `<ThemeProvider>` component will also enable dark mode for the app's background. :::warning Setting the dark mode this way only works if you are using [the default palette](/material-ui/customization/default-theme/). If you have a custom palette, make sure that you have the correct values based on the `mode`. The next section explains how to do this. ::: ## Dark mode with a custom palette To use custom palettes for light and dark modes, you can create a function that will return the correct palette depending on the selected mode, as shown here: ```ts const getDesignTokens = (mode: PaletteMode) => ({ palette: { mode, ...(mode === 'light' ? { // palette values for light mode primary: amber, divider: amber[200], text: { primary: grey[900], secondary: grey[800], }, } : { // palette values for dark mode primary: deepOrange, divider: deepOrange[700], background: { default: deepOrange[900], paper: deepOrange[900], }, text: { primary: '#fff', secondary: grey[500], }, }), }, }); ``` You can see on the example that there are different colors used based on whether the mode is light or dark. The next step is to use this function when creating the theme. ```tsx export default function App() { const [mode, setMode] = React.useState<PaletteMode>('light'); const colorMode = React.useMemo( () => ({ // The dark mode switch would invoke this method toggleColorMode: () => { setMode((prevMode: PaletteMode) => prevMode === 'light' ? 'dark' : 'light', ); }, }), [], ); // Update the theme only if the mode changes const theme = React.useMemo(() => createTheme(getDesignTokens(mode)), [mode]); return ( <ColorModeContext.Provider value={colorMode}> <ThemeProvider theme={theme}> <Page /> </ThemeProvider> </ColorModeContext.Provider> ); } ``` Here is a fully working example: {{"demo": "DarkThemeWithCustomPalette.js", "defaultCodeOpen": false}} ## Toggling color mode To give your users a way to toggle between modes, you can add React's context to a button's `onClick` event, as shown in the following demo: {{"demo": "ToggleColorMode.js", "defaultCodeOpen": false}} ## System preference Users might have a preference for light or dark mode that they've set through their operating system—either systemwide, or for a single user agent. You can make use of this preference with the [useMediaQuery](/material-ui/react-use-media-query/) hook and the [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) media query. The following demo shows how to enable dark mode automatically by checking for the user's preference in their OS or browser settings: ```jsx import * as React from 'react'; import useMediaQuery from '@mui/material/useMediaQuery'; import { createTheme, ThemeProvider } from '@mui/material/styles'; import CssBaseline from '@mui/material/CssBaseline'; function App() { const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)'); const theme = React.useMemo( () => createTheme({ palette: { mode: prefersDarkMode ? 'dark' : 'light', }, }), [prefersDarkMode], ); return ( <ThemeProvider theme={theme}> <CssBaseline /> <Routes /> </ThemeProvider> ); } ```
3,377
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/default-theme/DefaultTheme.js
import * as React from 'react'; import Box from '@mui/material/Box'; import Divider from '@mui/material/Divider'; import { createTheme, styled } from '@mui/material/styles'; import FormControlLabel from '@mui/material/FormControlLabel'; import Switch from '@mui/material/Switch'; import { useTranslate } from 'docs/src/modules/utils/i18n'; import ThemeViewer, { useNodeIdsLazy, } from 'docs/src/modules/components/ThemeViewer'; import { blue, grey } from 'docs/src/modules/brandingTheme'; const StyledSwitch = styled(Switch)(({ theme }) => [ { display: 'flex', padding: 0, width: 32, height: 20, borderRadius: 99, '&:active': { '& .MuiSwitch-thumb': { width: 16, }, '& .MuiSwitch-switchBase.Mui-checked': { transform: 'translateX(9px)', }, }, '& .MuiSwitch-switchBase': { padding: 2, '&.Mui-checked': { transform: 'translateX(12px)', color: '#FFF', '& + .MuiSwitch-track': { opacity: 1, backgroundColor: blue[500], }, }, }, '& .MuiSwitch-thumb': { width: 16, height: 16, borderRadius: 99, transition: theme.transitions.create(['width'], { duration: 200, }), }, '& .MuiSwitch-track': { borderRadius: 16 / 2, opacity: 1, backgroundColor: grey[400], boxSizing: 'border-box', }, [`:where(${theme.vars ? '[data-mui-color-scheme="dark"]' : '.mode-dark'}) &`]: { '& .MuiSwitch-switchBase': { '&.Mui-checked': { '& + .MuiSwitch-track': { backgroundColor: blue[500], }, }, }, '& .MuiSwitch-track': { backgroundColor: grey[700], }, }, }, ]); function DefaultTheme() { const [checked, setChecked] = React.useState(false); const [expandPaths, setExpandPaths] = React.useState(null); const t = useTranslate(); const [darkTheme, setDarkTheme] = React.useState(false); React.useEffect(() => { let expandPath; decodeURI(document.location.search.slice(1)) .split('&') .forEach((param) => { const [name, value] = param.split('='); if (name === 'expand-path') { expandPath = value; } }); if (!expandPath) { return; } setExpandPaths( expandPath .replace('$.', '') .split('.') .reduce((acc, path) => { const last = acc.length > 0 ? `${acc[acc.length - 1]}.` : ''; acc.push(last + path); return acc; }, []), ); }, []); const data = React.useMemo(() => { return createTheme({ palette: { mode: darkTheme ? 'dark' : 'light' }, }); }, [darkTheme]); const allNodeIds = useNodeIdsLazy(data); React.useDebugValue(allNodeIds); React.useEffect(() => { if (checked) { // in case during the event handler allNodeIds wasn't computed yet setExpandPaths(allNodeIds); } }, [checked, allNodeIds]); return ( <Box sx={{ width: '100%' }}> <Box sx={{ display: 'flex', gap: 2, mb: 3 }}> <FormControlLabel label={t('expandAll')} sx={{ m: 0, flexDirection: 'row-reverse', gap: 1, '& .MuiFormControlLabel-label': { fontFamily: 'IBM Plex Sans', color: 'text.secondary', }, }} control={ <StyledSwitch size="small" checked={checked} onChange={(event) => { setChecked(event.target.checked); setExpandPaths(event.target.checked ? allNodeIds : []); }} /> } /> <Divider orientation="vertical" flexItem /> <FormControlLabel label={t('useDarkTheme')} sx={{ m: 0, flexDirection: 'row-reverse', gap: 1, '& .MuiFormControlLabel-label': { fontFamily: 'IBM Plex Sans', color: 'text.secondary', }, }} control={ <StyledSwitch size="small" checked={darkTheme} onChange={(event) => { setDarkTheme(event.target.checked); }} /> } /> </Box> <ThemeViewer data={data} expandPaths={expandPaths} /> </Box> ); } export default DefaultTheme;
3,378
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/default-theme/default-theme.md
# Default theme viewer <p class="description">Check out how the theme object looks like with the default values.</p> If you want to learn more about how the theme is assembled, take a look at [`material-ui/style/createTheme.js`](https://github.com/mui/material-ui/blob/-/packages/mui-material/src/styles/createTheme.js), and the related imports which `createTheme` uses. :::success You can play with the documentation theme object in your browser console, as the `theme` variable is exposed on all the documentation pages. ::: :::warning Please note that **the documentation site is using a custom theme** (MUI's branding). ::: <hr/> {{"demo": "DefaultTheme.js", "hideToolbar": true, "bg": "inline"}}
3,379
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/density/DensityTool.js
import * as React from 'react'; import { useTheme } from '@mui/material/styles'; import Grid from '@mui/material/Grid'; import Input from '@mui/material/Input'; import Typography from '@mui/material/Typography'; import Button from '@mui/material/Button'; import IconButton from '@mui/material/IconButton'; import FormControlLabel from '@mui/material/FormControlLabel'; import Switch from '@mui/material/Switch'; import IncreaseIcon from '@mui/icons-material/AddCircleOutline'; import DecreaseIcon from '@mui/icons-material/RemoveCircleOutline'; import { DispatchContext } from 'docs/src/modules/components/ThemeContext'; import { useTranslate } from 'docs/src/modules/utils/i18n'; const minSpacing = 0; const maxSpacing = 20; export default function DensityTool() { const dispatch = React.useContext(DispatchContext); const handleDensityChange = (event) => { dispatch({ type: 'SET_DENSE', payload: event.target.checked, }); }; const handleSpacingChange = (event, value) => { let spacing = value || +event.target.value; // If the entered value is greater than maxSpacing, setting up maxSpacing as value if (spacing > maxSpacing) { spacing = maxSpacing; } // If the entered value is less than minSpacing, setting up minSpacing as value if (spacing < minSpacing) { spacing = minSpacing; } dispatch({ type: 'SET_SPACING', payload: spacing, }); }; const increaseSpacing = () => { dispatch({ type: 'INCREASE_SPACING' }); }; const decreaseSpacing = () => { dispatch({ type: 'DECREASE_SPACING' }); }; const resetDensity = () => { dispatch({ type: 'RESET_DENSITY' }); }; const theme = useTheme(); // Use unstable_toUnitless in the future if need to handle custom themes const spacingUnit = parseFloat(theme.spacing(1)); const t = useTranslate(); return ( <Grid container spacing={2}> <Grid container item> <FormControlLabel control={ <Switch checked={theme.dense} onChange={handleDensityChange} value="dense" color="secondary" /> } label={t('useHighDensity')} /> </Grid> <Grid container item alignItems="center" spacing={2}> <Grid item> <Typography id="input-slider" gutterBottom> {t('spacingUnit')} </Typography> </Grid> <Grid item> <IconButton aria-label={t('decreaseSpacing')} onClick={decreaseSpacing} disabled={spacingUnit === minSpacing} > <DecreaseIcon /> </IconButton> <Input value={spacingUnit} margin="dense" onChange={handleSpacingChange} inputProps={{ step: 1, min: minSpacing, max: maxSpacing, type: 'number', 'aria-labelledby': 'input-slider', }} /> <IconButton aria-label={t('increaseSpacing')} onClick={increaseSpacing} disabled={spacingUnit === maxSpacing} > <IncreaseIcon /> </IconButton> </Grid> </Grid> <Grid item> <Button variant="contained" onClick={resetDensity}> {t('resetDensity')} </Button> </Grid> </Grid> ); }
3,380
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/density/density.md
# Density <p class="description">How to apply density to Material UI components.</p> ## Applying density This section explains how to apply density. It doesn't cover potential use cases, or considerations for using density in your application. The Material Design guidelines have a [comprehensive guide](https://m2.material.io/design/layout/applying-density.html) covering these topics in more detail. ## Implementing density Higher density can be applied to some components via props. The component pages have at least one example using the respective component with higher density applied. Depending on the component, density is applied either via lower spacing, or simply by reducing the size. The following components have props applying higher density: - [Button](/material-ui/api/button/) - [Fab](/material-ui/api/fab/) - [FilledInput](/material-ui/api/filled-input/) - [FormControl](/material-ui/api/form-control/) - [FormHelperText](/material-ui/api/form-helper-text/) - [IconButton](/material-ui/api/icon-button/) - [InputBase](/material-ui/api/input-base/) - [InputLabel](/material-ui/api/input-label/) - [ListItem](/material-ui/api/list-item/) - [OutlinedInput](/material-ui/api/outlined-input/) - [Table](/material-ui/api/table/) - [TextField](/material-ui/api/text-field/) - [Toolbar](/material-ui/api/toolbar/) ## Explore theme density This tool allows you to apply density via spacing and component props. You can browse around and see how this applies to the overall feel of Material UI components. If you enable high density a custom theme is applied to the docs. This theme is only for demonstration purposes. You _should not_ apply this theme to your whole application as this might negatively impact user experience. The [Material Design guidelines](https://m2.material.io/design/layout/applying-density.html) has examples for when not to apply density. The theme is configured with the following options: ```js const theme = createTheme({ components: { MuiButton: { defaultProps: { size: 'small', }, }, MuiFilledInput: { defaultProps: { margin: 'dense', }, }, MuiFormControl: { defaultProps: { margin: 'dense', }, }, MuiFormHelperText: { defaultProps: { margin: 'dense', }, }, MuiIconButton: { defaultProps: { size: 'small', }, }, MuiInputBase: { defaultProps: { margin: 'dense', }, }, MuiInputLabel: { defaultProps: { margin: 'dense', }, }, MuiListItem: { defaultProps: { dense: true, }, }, MuiOutlinedInput: { defaultProps: { margin: 'dense', }, }, MuiFab: { defaultProps: { size: 'small', }, }, MuiTable: { defaultProps: { size: 'small', }, }, MuiTextField: { defaultProps: { margin: 'dense', }, }, MuiToolbar: { defaultProps: { variant: 'dense', }, }, }, }); ``` {{"demo": "DensityTool.js", "hideToolbar": true}}
3,381
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/DevTools.js
import * as React from 'react'; import Slider from '@mui/material/Slider'; export default function DevTools() { return ( <Slider defaultValue={30} sx={{ width: 300, color: 'success.main', '& .MuiSlider-thumb': { borderRadius: '1px', }, }} /> ); }
3,382
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/DevTools.tsx
import * as React from 'react'; import Slider from '@mui/material/Slider'; export default function DevTools() { return ( <Slider defaultValue={30} sx={{ width: 300, color: 'success.main', '& .MuiSlider-thumb': { borderRadius: '1px', }, }} /> ); }
3,383
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/DevTools.tsx.preview
<Slider defaultValue={30} sx={{ width: 300, color: 'success.main', '& .MuiSlider-thumb': { borderRadius: '1px', }, }} />
3,384
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/DynamicCSS.js
import * as React from 'react'; import { alpha, styled } from '@mui/material/styles'; import Slider from '@mui/material/Slider'; import FormControlLabel from '@mui/material/FormControlLabel'; import Switch from '@mui/material/Switch'; const StyledSlider = styled(Slider, { shouldForwardProp: (prop) => prop !== 'success', })(({ success, theme }) => ({ width: 300, ...(success && { color: theme.palette.success.main, '& .MuiSlider-thumb': { [`&:hover, &.Mui-focusVisible`]: { boxShadow: `0px 0px 0px 8px ${alpha(theme.palette.success.main, 0.16)}`, }, [`&.Mui-active`]: { boxShadow: `0px 0px 0px 14px ${alpha(theme.palette.success.main, 0.16)}`, }, }, }), })); export default function DynamicCSS() { const [success, setSuccess] = React.useState(false); const handleChange = (event) => { setSuccess(event.target.checked); }; return ( <React.Fragment> <FormControlLabel control={ <Switch checked={success} onChange={handleChange} color="primary" value="dynamic-class-name" /> } label="Success" /> <StyledSlider success={success} defaultValue={30} sx={{ mt: 1 }} /> </React.Fragment> ); }
3,385
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/DynamicCSS.tsx
import * as React from 'react'; import { alpha, styled } from '@mui/material/styles'; import Slider, { SliderProps } from '@mui/material/Slider'; import FormControlLabel from '@mui/material/FormControlLabel'; import Switch from '@mui/material/Switch'; interface StyledSliderProps extends SliderProps { success?: boolean; } const StyledSlider = styled(Slider, { shouldForwardProp: (prop) => prop !== 'success', })<StyledSliderProps>(({ success, theme }) => ({ width: 300, ...(success && { color: theme.palette.success.main, '& .MuiSlider-thumb': { [`&:hover, &.Mui-focusVisible`]: { boxShadow: `0px 0px 0px 8px ${alpha(theme.palette.success.main, 0.16)}`, }, [`&.Mui-active`]: { boxShadow: `0px 0px 0px 14px ${alpha(theme.palette.success.main, 0.16)}`, }, }, }), })); export default function DynamicCSS() { const [success, setSuccess] = React.useState(false); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { setSuccess(event.target.checked); }; return ( <React.Fragment> <FormControlLabel control={ <Switch checked={success} onChange={handleChange} color="primary" value="dynamic-class-name" /> } label="Success" /> <StyledSlider success={success} defaultValue={30} sx={{ mt: 1 }} /> </React.Fragment> ); }
3,386
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/DynamicCSS.tsx.preview
<React.Fragment> <FormControlLabel control={ <Switch checked={success} onChange={handleChange} color="primary" value="dynamic-class-name" /> } label="Success" /> <StyledSlider success={success} defaultValue={30} sx={{ mt: 1 }} /> </React.Fragment>
3,387
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/DynamicCSSVariables.js
import * as React from 'react'; import { styled } from '@mui/material/styles'; import Slider from '@mui/material/Slider'; import FormControlLabel from '@mui/material/FormControlLabel'; import Switch from '@mui/material/Switch'; const CustomSlider = styled(Slider)({ width: 300, color: 'var(--color)', '& .MuiSlider-thumb': { [`&:hover, &.Mui-focusVisible`]: { boxShadow: '0px 0px 0px 8px var(--box-shadow)', }, [`&.Mui-active`]: { boxShadow: '0px 0px 0px 14px var(--box-shadow)', }, }, }); const successVars = { '--color': '#4caf50', '--box-shadow': 'rgb(76, 175, 80, .16)', }; const defaultVars = { '--color': '#1976d2', '--box-shadow': 'rgb(25, 118, 210, .16)', }; export default function DynamicCSSVariables() { const [vars, setVars] = React.useState(defaultVars); const handleChange = (event) => { setVars(event.target.checked ? successVars : defaultVars); }; return ( <React.Fragment> <FormControlLabel control={ <Switch checked={vars === successVars} onChange={handleChange} color="primary" value="dynamic-class-name" /> } label="Success" /> <CustomSlider style={vars} defaultValue={30} sx={{ mt: 1 }} /> </React.Fragment> ); }
3,388
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/DynamicCSSVariables.tsx
import * as React from 'react'; import { styled } from '@mui/material/styles'; import Slider from '@mui/material/Slider'; import FormControlLabel from '@mui/material/FormControlLabel'; import Switch from '@mui/material/Switch'; const CustomSlider = styled(Slider)({ width: 300, color: 'var(--color)', '& .MuiSlider-thumb': { [`&:hover, &.Mui-focusVisible`]: { boxShadow: '0px 0px 0px 8px var(--box-shadow)', }, [`&.Mui-active`]: { boxShadow: '0px 0px 0px 14px var(--box-shadow)', }, }, }); const successVars = { '--color': '#4caf50', '--box-shadow': 'rgb(76, 175, 80, .16)', } as React.CSSProperties; const defaultVars = { '--color': '#1976d2', '--box-shadow': 'rgb(25, 118, 210, .16)', } as React.CSSProperties; export default function DynamicCSSVariables() { const [vars, setVars] = React.useState<React.CSSProperties>(defaultVars); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { setVars(event.target.checked ? successVars : defaultVars); }; return ( <React.Fragment> <FormControlLabel control={ <Switch checked={vars === successVars} onChange={handleChange} color="primary" value="dynamic-class-name" /> } label="Success" /> <CustomSlider style={vars} defaultValue={30} sx={{ mt: 1 }} /> </React.Fragment> ); }
3,389
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/DynamicCSSVariables.tsx.preview
<React.Fragment> <FormControlLabel control={ <Switch checked={vars === successVars} onChange={handleChange} color="primary" value="dynamic-class-name" /> } label="Success" /> <CustomSlider style={vars} defaultValue={30} sx={{ mt: 1 }} /> </React.Fragment>
3,390
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/GlobalCssOverride.js
import * as React from 'react'; import GlobalStyles from '@mui/material/GlobalStyles'; export default function GlobalCssOverride() { return ( <React.Fragment> <GlobalStyles styles={{ h1: { color: 'grey' } }} /> <h1>Grey h1 element</h1> </React.Fragment> ); }
3,391
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/GlobalCssOverride.tsx
import * as React from 'react'; import GlobalStyles from '@mui/material/GlobalStyles'; export default function GlobalCssOverride() { return ( <React.Fragment> <GlobalStyles styles={{ h1: { color: 'grey' } }} /> <h1>Grey h1 element</h1> </React.Fragment> ); }
3,392
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/GlobalCssOverride.tsx.preview
<React.Fragment> <GlobalStyles styles={{ h1: { color: 'grey' } }} /> <h1>Grey h1 element</h1> </React.Fragment>
3,393
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/OverrideCallbackCssBaseline.js
import * as React from 'react'; import CssBaseline from '@mui/material/CssBaseline'; import { ThemeProvider, createTheme } from '@mui/material/styles'; const theme = createTheme({ palette: { success: { main: '#ff0000', }, }, components: { MuiCssBaseline: { styleOverrides: (themeParam) => ` h1 { color: ${themeParam.palette.success.main}; } `, }, }, }); export default function OverrideCallbackCssBaseline() { return ( <ThemeProvider theme={theme}> <CssBaseline /> <h1>h1 element</h1> </ThemeProvider> ); }
3,394
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/OverrideCallbackCssBaseline.tsx
import * as React from 'react'; import CssBaseline from '@mui/material/CssBaseline'; import { ThemeProvider, createTheme } from '@mui/material/styles'; const theme = createTheme({ palette: { success: { main: '#ff0000', }, }, components: { MuiCssBaseline: { styleOverrides: (themeParam) => ` h1 { color: ${themeParam.palette.success.main}; } `, }, }, }); export default function OverrideCallbackCssBaseline() { return ( <ThemeProvider theme={theme}> <CssBaseline /> <h1>h1 element</h1> </ThemeProvider> ); }
3,395
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/OverrideCallbackCssBaseline.tsx.preview
<ThemeProvider theme={theme}> <CssBaseline /> <h1>h1 element</h1> </ThemeProvider>
3,396
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/OverrideCssBaseline.js
import * as React from 'react'; import CssBaseline from '@mui/material/CssBaseline'; import { ThemeProvider, createTheme } from '@mui/material/styles'; const theme = createTheme({ components: { MuiCssBaseline: { styleOverrides: ` h1 { color: grey; } `, }, }, }); export default function OverrideCssBaseline() { return ( <ThemeProvider theme={theme}> <CssBaseline /> <h1>Grey h1 element</h1> </ThemeProvider> ); }
3,397
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/OverrideCssBaseline.tsx
import * as React from 'react'; import CssBaseline from '@mui/material/CssBaseline'; import { ThemeProvider, createTheme } from '@mui/material/styles'; const theme = createTheme({ components: { MuiCssBaseline: { styleOverrides: ` h1 { color: grey; } `, }, }, }); export default function OverrideCssBaseline() { return ( <ThemeProvider theme={theme}> <CssBaseline /> <h1>Grey h1 element</h1> </ThemeProvider> ); }
3,398
0
petrpan-code/mui/material-ui/docs/data/material/customization
petrpan-code/mui/material-ui/docs/data/material/customization/how-to-customize/OverrideCssBaseline.tsx.preview
<ThemeProvider theme={theme}> <CssBaseline /> <h1>Grey h1 element</h1> </ThemeProvider>
3,399