material-ui: Add useBreakpointValue hook
- I have searched the issues of this repository and believe that this is not a duplicate.
Summary 💡
Provide a JavaScript API as a counterpart to the CSS sx breakpoint’s API.
Examples 🌈
function MyApp() {
const elevation = useBreakpointValue({ xs: 1, md: 2 });
return <AppBar elevation={elevation} sx={{ mb: { xs: 1, md: 2 } }}>...</AppBar>;
}
Internally, useBreakpointValue would use useMediaQuery or useBreakpoint (probably better).
Motivation 🔦
We have started to surface the need for it in https://github.com/mui-org/material-ui/issues/15561#issuecomment-674454140. The hook can be used anytime a value needs to be determined based on the breakpoints. This comment https://github.com/mui-org/material-ui/issues/17000#issuecomment-740159615 triggered the idea around opening this issue. I think that this hook is best for props that are already dependent on JavaScript logic.
One could argue that many of the CSS properties could be made responsive, e.g. the color prop. However, it might be overkill, we could use this hook as an escape hatch.
We have been discussing the idea to remove the <HiddenCss> helper as the Box covers most of the usage thanks to the sx’s display feature. I think that this JS counterpart can solve the <HiddenJs> part of the migration issue: https://github.com/mui-org/material-ui/issues/19704#issuecomment-612034247.
Benchmarks
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 24
- Comments: 15 (6 by maintainers)
To get the largest matching breakpoint, I use the following:
What about changing
Tabs,AppBarorientation fromhorizontaltoverticaldepending on the breakpoint.This is something Chakra supports out of the box.
The general point here is that currently in MUI it is difficult to make some values responsive, https://github.com/mui-org/material-ui/issues/6140 was a step in the right direction, but it only applies to the
Gridcomponent.Anyway heres a quick one I created for my own use - has not been tested in production to any great extent.