If you are using Material UI in your react app as a styling library, then it's possible doing this through two methods.
So, before I explain the methods, I'll just quickly explain the 6 terms that are foundational in styling responsive designs using Material UI
They are - xs,sm,md,lg,xl
as the name suggests,
xs - xtra small, sm - small, md - medium, lg - large and xl - xtra large, these are just breakpoint variables for device sizes.
Ranging from 0 - 1920px, where each breakpoint represents values less than it's absolute value.
So, sm = 600px, then it means all devices from 0 - 600 are in the sm category and this concept is applied to other breakpoint variables. Check this out
So, you can use it in a Grid, or a Container, and it will adapt accordingly.
You can use it in styling, a Material UIi component as well.
For eg -
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],
},
},
});
So, all the sizes which are from xs to md will have the secondary color, and from md to lg will have primary color and device sizes above lg will have the green color.
You can play around and do this for number of conditional styles to achieve responsive designs.
If you want to render a completely different component, then you can use the useMediaQuery hook that Material UI provides.
For eg -
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>;
}
Here, if the device sizes, match the breakpoints from sm - xl, then the matches constant will be true and if less than sm, it'll be false.
The hook return a boolean value, for a breakpoint we pass it.
All, in all I find these two simple methods, really powerful for designing responsive screens.