Mohamed Atef
21 Oct 2021
React js
the best way to use the media queries or breakpoints in your code is using the default Material UI breakpoints like this
Class component
import React from 'react';
import { withStyles } from '@material-ui/core';
const styles = (theme) => ({
root:{
backgroundColor: '#000',
[theme.breakpoints.up('md')]:{
maxWidth: '800px',
},
[theme.breakpoints.down('md')]:{
maxWidth: '90%',
},
}
});
class Homepage extends React.Component {
render(){
const { classes } = this.props;
return(
<div className={classes.root}>
</div>
);
}
}
export default withStyles(styles)(Homepage);
And in the functional component, you do the same thing but using a function called makeStyles to be like this
import React from 'react';
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles(() => ({
root: {
backgroundColor: '#000',
[theme.breakpoints.up('md')]:{
maxWidth: '800px',
},
[theme.breakpoints.down('md')]:{
maxWidth: '90%',
},
}
}));
const Homepage = () => {
const classes = useStyles();
return (
<div className={classes.root}>
</div>
);
}
export default Homepage;
to make. your custom media query into the functions makeStyles or withStyles you will do it like this
import React from 'react';
import { withStyles } from '@material-ui/core';
const styles = (theme) => ({
root:{
['@media screen and (min-width: 1500px)']:{
maxWidth: '675px'
},
['@media screen and (min-width: 1200px) and (max-width: 1500px)']:{
maxWidth: '580px'
},
['@media screen and (min-width: 1000px) and (max-width: 1200px)']:{
maxWidth: '480px'
},
}
});
class Homepage extends React.Component {
render(){
const { classes } = this.props;
return(
<div className={classes.root}>
</div>
);
}
}
export default withStyles(styles)(Homepage);
but the way above can return some warnings, it will be working fine but in some Reactjs versions it will be called like useless media query however the users and developers will be able to watch the effect and it will be working fine so there is only one more way by using regular CSS files and no problem or warnings in this way
import React from 'react';
import { withStyles } from '@material-ui/core';
import './styles.css';
const styles = (theme) => ({
root:{
backgroundColor: '#000',
}
});
class Homepage extends React.Component {
render(){
const { classes } = this.props;
return(
<div className={classes.root} id="custom-homepage-root">
</div>
);
}
}
export default withStyles(styles)(Homepage);
in style.css
@media screen and (min-width: 1500px){
#custom-homepage-root { max-width: 675px; }
}
@media screen and (max-width: 1000px){
#custom-homepage-root { max-width: 375px; }
}
that's all, & maybe in the feature there will be more ways of styling, if you have any questions please let me know in the comments below, Good Luck
No Comments to show
© 2024 Copyrights reserved for web-brackets.com