Is there a way for me to change my Typography align property based on the pre-defined breakpoints?
For example:
<Typography
align={{ xs: 'left', sm: 'left', md: 'left', lg: 'right', xl: 'right' }}>
The following will cause my page to display nothing but white. I usually use that syntax to work with margins in the Box class and it works fine.
You can't set the Typography align attribute with an object.
As specified in the documentation for the Typography component, the align attribute can only be 'inherit' | 'left' | 'center' | 'right' | 'justify'.
Instead, you could use the withWidth HOC:
Sometimes you might want to change the React rendering tree based on the breakpoint value. We provide a withWidth() higher-order component for this use case.
withWidth injects a width property into your component that gives you access to the current breakpoint value. This allows you to render different props or content based on screen size.
function ResponsiveTypography({ width }) {
// This is equivalent to theme.breakpoints.down("md")
const isSmallScreen = /xs|sm|md/.test(width);
const typographyProps = {
align: isSmallScreen ? "left" : "right"
};
return (
<Typography {...typographyProps}>
Some text
</Typography>
);
}
export default withWidth()(ResponsiveTypography);
This seem to work for me, MUI v5:
import { useTheme } from '#mui/material/styles';
...
const theme = useTheme();
...
<Typography
sx={{
textAlign: 'center',
[theme.breakpoints.up('md')]: {
textAlign: 'left',
},
[theme.breakpoints.up('xl')]: {
textAlign: 'right',
},
[theme.breakpoints.between('sm', 'md')]: {
}
[theme.breakpoints.not('md')]: {
}
}}
>
Breakpoints API
https://mui.com/material-ui/customization/breakpoints/
With MUI v5, I found that sx prop has the ability to do breakpoints without importing the theme object (like in #atazmin's answer).
The breakpoints are mobile-first and get translated to min-width Media Queries. You can specify the starting value with xs and change it by breakpoint using lg and up.
<Typography
sx={{
textAlign: {
xs: 'left',
lg: 'right',
},
}}
>
Related
I use Container and it needs to be different size for mobile and for desktop.
How can I have the Container maxWidth different size based on Breakpoints like this:
<Container maxWidth={{xs:"lg", lg:"md"}}>
instead of using the useStyle and adding a className.
I found most of answer related to functional component, but if you are using class component we can directly use like this. I like to use 'vh' and 'vw' as this unit is direclty adjustable to viewport.
<Container
sx={{
width: {
lg: '35vw',
md: '50vw',
xs: '70vw'
}
}}>
You can do that by using the sx prop which supports responsive values. The breakpoint values can be accessed in theme.breakpoints.values object. See the default theme here to know more.
const theme = useTheme();
<Container
sx={{
bgcolor: "wheat",
maxWidth: {
lg: theme.breakpoints.values["md"],
md: 80,
xs: 20
}
}}
>
<Box sx={{ bgcolor: "#cfe8fc", height: "100vh", width: "100%" }} />
</Container>
I'd like to create a reusable component using Material-UI's api (not using styled-components.) I got this far - and it almost works - but the settings that use theme variable don't work (e.g, bgcolor and padding). Am I doing something wrong - or is this not possible?
const BigPanel = styled(Box)({
display: 'flex',
width: '100%',
flexgrow: 1,
bgcolor: 'background.paper',
borderRadius: 10,
boxShadow:'1',
p:{ xs: 4, md: 8 }
});
The object passed to styled is intended to be CSS properties, but you have a mixture of CSS properties and Box props (bgcolor, p). Even the ones that are valid CSS properties (display, width) are also valid Box props, so the most straightforward solution is to specify all of them as props.
One way to handle this is to use defaultProps. This makes it very easy to override some of the props when using the component by specifying them explicitly as shown in the example below.
import React from "react";
import Box from "#material-ui/core/Box";
import CssBaseline from "#material-ui/core/CssBaseline";
import { styled } from "#material-ui/core/styles";
const BigPanel = styled(Box)({});
BigPanel.defaultProps = {
display: "flex",
width: "100%",
borderRadius: 10,
flexGrow: 1,
bgcolor: "background.paper",
p: { xs: 4, md: 8 },
boxShadow: "1"
};
export default function App() {
return (
<>
<CssBaseline />
<BigPanel>Default BigPanel</BigPanel>
<BigPanel bgcolor="primary.main" color="primary.contrastText">
BigPanel with explicit props
</BigPanel>
</>
);
}
In the example above, styled isn't really serving any purpose anymore except to create a new component type. Though it isn't less code, below is an alternative way to get the same effect without using styled:
const BigPanel = React.forwardRef(function BigPanel(props, ref) {
return <Box ref={ref} {...props} />;
});
BigPanel.defaultProps = {
display: "flex",
width: "100%",
borderRadius: 10,
flexGrow: 1,
bgcolor: "background.paper",
p: { xs: 4, md: 8 },
boxShadow: "1"
};
I want to increase the font size for the pagination part of the material table footer.
In the below image, I am able to change the font size of rows per page with the below code
[1]: https://i.stack.imgur.com/cjNmp.png
components={{
Pagination: props => (
<TablePagination
{...props}
SelectProps={{
style:{
fontSize: 20
}
}}
/>
)
}}
but still unable to change increase size of the whole underlined part
I styled both caption area using two different methods: One via toolbar styles and the other directly:
There is two parts in the results per page component and are a p by default
import makeStyles from "#material-ui/core/styles/makeStyles";
const useStyles = makeStyles({
caption: {
color: "green",
padding: 8,
border: "1px dashed grey",
fontSize: "0.875rem"
},
toolbar: {
"& > p:nth-of-type(2)": {
fontSize: "1.25rem",
color: "red",
fontWeight: 600
}
}
});
// then later
const classes = useStyles();
<TablePagination
// ...
classes={{
toolbar: classes.toolbar,
caption: classes.caption
}}
/>
Here is a codesandbox demo
How can I override the default value of the max-height property for the Popover component?
I tried to add style={{'maxHeight': '365px'}}, but nothing is changed:
<Popover
style={{'maxHeight': '365px'}}
className='notif-popover'
open={this.state.notifOpen}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
onRequestClose={this.handleRequestClose}
>
The only props that apply style are:
className string of classes and style object with styles.
Remember that these are applied to the root element (the Modal component).
Docs SourceCode (if you're using v1-beta). You can see in the sources that the remaining props are passed to the Modal component
const {
anchorEl,
anchorReference,
anchorPosition,
anchorOrigin,
children,
classes,
elevation,
getContentAnchorEl,
marginThreshold,
onEnter,
onEntering,
onEntered,
onExit,
onExiting,
onExited,
open,
PaperProps,
role,
transformOrigin,
transitionClasses,
transitionDuration,
...other
} = this.props;
<Modal show={open} BackdropInvisible {...other}>
You can see in the sources that MaterialUI uses the withStyles HoC from react-jss and has a styles object for the Paper component
export const styles = {
paper: {
position: 'absolute',
overflowY: 'auto',
overflowX: 'hidden',
// So we see the popover when it's empty.
// It's most likely on issue on userland.
minWidth: 16,
minHeight: 16,
maxWidth: 'calc(100vw - 32px)',
maxHeight: 'calc(100vh - 32px)'
maxHeight: 'calc(100vh - 32px)'
This is bound to a class paper and then passed to the classes prop and applied to the Paper component.
Solution:
Use the className prop on the root element with nested selector that targets the Paper component (inspect and see on which element it applies the class).
Example of possible selector (should definitely use a better one, inspect element)
.rootElement > * { max-height: '375px' }
and then you'd do <Popover className='rootElement' />
You should really override the style while building the theme...
createMuiTheme({
overrides: {
MuiTooltip: {
tooltip: {
fontSize: '1rem',
backgroundColor: '#000',
}
}
}
})
This CSS override seems to work for me:
.writeYourOwnClasHere {
.MuiPaper-root-6 {
padding: 30px;
color: pink;
}
}
Btw, it's an unbelievably crappy API.
I am using MUI components in ReactJs project, for some reason I need customization in some components to make it responsive according to screen width.
I have added media query and pass it as style attribute in the components but not working, any idea?
I am using code like this:
const drawerWidth = {
width: '50%',
'#media(minWidth: 780px)' : {
width: '80%'
}
}
<Drawer
.....
containerStyle = {drawerStyle}
>
</Drawer>
Code is working for web only, on mobile device no effect. Even CSS code is not applying I've checked in developer console. I am using MUI version 0.18.7.
Any help would be appreciated.
PS: As per requirement I need to make some changes according to screen size using CSS.
By using the breakpoints attribute of the theme, you can utilize the same breakpoints used for the Grid and Hidden components directly in your component.
API
theme.breakpoints.up(key) => media query
Arguments
key (String | Number): A breakpoint key (xs, sm, etc.) or a screen width number in pixels.
Returns
media query: A media query string ready to be used with JSS.
Examples
const styles = theme => ({
root: {
backgroundColor: 'blue',
[theme.breakpoints.up('md')]: {
backgroundColor: 'red',
},
},
});
for more information check this out
You were almost right, but you need to use min-width instead of minWidth:
const styles = {
drawerWidth: {
width: '50%',
'#media (min-width: 780px)': {
width: '80%'
}
}
}
You have a typo in the media query. You should use the following syntax and it will work as expected:
const drawerWidth = {
width: '50%',
'#media (min-width: 780px)' : {
width: '80%'
}
}
instead of
const drawerWidth = {
width: '50%',
'#media(minWidth: 780px)' : {
width: '80%'
}
}
In MUI v5, breakpoints can be declared in sx props by specifying an object where the keys are the breakpoint names and the values are the CSS values.
You can see MUI default breakpoints here. The breakpoint names and values can be overrided using createTheme():
const theme = createTheme({
breakpoints: {
values: {
xxs: 0, // small phone
xs: 300, // phone
sm: 600, // tablets
md: 900, // small laptop
lg: 1200, // desktop
xl: 1536 // large screens
}
}
});
return (
<ThemeProvider theme={theme}>
<Box
sx={{
// specify one value that is applied in all breakpoints
color: 'white',
// specify multiple values applied in specific breakpoints
backgroundColor: {
xxs: "red",
xs: "orange",
sm: "yellow",
md: "green",
lg: "blue",
xl: "purple"
}
}}
>
Box 1
</Box>
</ThemeProvider>
);
In the example above, xs: "orange" means set the Box color to orange if the screen width is inside xs range [300, 600).
You can also set the breakpoints using an array consists of the values from the smallest to largest breakpoint:
return (
<ThemeProvider theme={theme}>
<Box
sx={{
backgroundColor: [
"red",
"orange",
// unset, screen width inside this breakpoint uses the last non-null value
null,
"green",
"blue",
"purple"
]
}}
>
Box 2
</Box>
</ThemeProvider>
);
Similiar answer to #Lipunov's, based on #nbkhope's comment
const styles = {
drawerWidth: {
width: '50%',
[theme.breakpoints.up(780)]: {
width: '80%'
}
}
}
I've solved this problem by doing something like this:
const dropzoneStyles =
window.screen.availWidth < 780 ?
{ 'width': '150px', 'height': '150px', 'border': 'none', 'borderRadius': '50%' }
: { 'width': '200px', 'height': '200px', 'border': 'none', 'borderRadius': '50%' };
and then appending it as an attribute in the Material UI element:
<Dropzone style={dropzoneStyles} onDrop={this.handleDrop.bind(this)}>
So the key is to find out the window screen using window.screen.availWidth. And you would be doing this in the render() function. Hope that helps!
In the style property on React you can only define properties that you can define in a normal DOM element (You can't include media queries for example)
The way you can include media queries for that component would be passing a class name to the Drawer Component
<Drawer containerClassName="someClass" />
And then in a CSS file you do something like this
#media(min-width: 780px){
.someClass {
width: 50%!important;
}
}
In my case I just needed the breakpoint on one component and I found the createTheme approach a little bit too much. I ended using useMediaQuery and useTheme.
I see that with useMEdiaQuery you can be quite granular
import { useTheme } from '#mui/material/styles';
import useMediaQuery from '#mui/material/useMediaQuery';
const Component = () => {
const theme = useTheme();
const matchesSM = useMediaQuery(theme.breakpoints.down('sm'));
const matchesMD = useMediaQuery(theme.breakpoints.only('md'));
const dynamicStyles = {
...matchesSM && {margin: '10px 0'},
...matchesMD && {margin: '20px 0'}
}
return (
<Grid item xs={12} md={4} sx={{...dynamicStyles}}>
<div>Children</div>
</Grid>
)
}
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.down(key)
theme.breakpoints.only(key)
theme.breakpoints.not(key)
theme.breakpoints.between(start, end)
In the following stress test, you can update the theme color and the background-color property live:
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],
},
},
});
<Root>
<Typography>down(md): red</Typography>
<Typography>up(md): blue</Typography>
<Typography>up(lg): green</Typography>
</Root>
Know more
Create a variable and then use that variable anywhere in the function
import React from 'react';
import { createMuiTheme, ThemeProvider, useTheme } from '#materialui/core/styles';
import useMediaQuery from '#material-ui/core/useMediaQuery';
function MyComponent() {
const theme = useTheme();
const matches = useMediaQuery(theme.breakpoints.up('sm')); // Variable for media query
return <span hidden={matches}>Hidden on screen size greater then sm </span>;
}
const theme = createMuiTheme();
export default function ThemeHelper() {
return (
<ThemeProvider theme={theme}>
<MyComponent />
</ThemeProvider>
);
}