I've tried using ImageList component instead of Grid as I just need a grid of photos with titles and it seems to be the whole point of ImageList. My issue is that unlike with Grid I cannot pass breakpoint props for different screen sizes (which I find weird as this would seem logical) so that I can get different count of columns on different screens. What would be the best approach to adjust number of columns based on screen size?
ImageList uses CSS grid and needs the col prop to set the grid-template-columns but without any responsive API baked in. You can swap the ImageList with a Box component with the display set to grid, and uses the sx prop to declare the column template value depend on the screen size, but first let define some breakpoints:
const theme = createTheme({
breakpoints: {
values: {
mobile: 0,
bigMobile: 350,
tablet: 650,
desktop: 900
}
}
});
Then in the component, you can start using it like this:
import ImageListItem, { imageListItemClasses } from "#mui/material/ImageListItem";
<ThemeProvider theme={theme}>
<Box
sx={{
display: "grid",
gridTemplateColumns: {
mobile: "repeat(1, 1fr)",
bigMobile: "repeat(2, 1fr)",
tablet: "repeat(3, 1fr)",
desktop: "repeat(4, 1fr)"
}
// standard variant from here:
// https://github.com/mui-org/material-ui/blob/3e679ac9e368aeb170d564d206d59913ceca7062/packages/mui-material/src/ImageListItem/ImageListItem.js#L42-L43
[`& .${imageListItemClasses.root}`]: {
display: "flex",
flexDirection: "column"
}
}}
>
{itemData.map((item) => <ImageListItem {...}/>)}
</Box>
</ThemeProvider>
Live Demo
References
Media queries in MUI components
https://mui.com/customization/breakpoints/#main-content
I used the useMediaQuery hook to get the cols props for the ImageList component.
import { ImageList, ImageListItem, useMediaQuery } from '#mui/material';
function Gallery() {
const matches = useMediaQuery('(min-width:600px)');
return (
<ImageList cols={matches ? 3 : 2} variant="masonry">
<ImageListItem>
...
</ImageListItem>
</ImageList>
);
}
I spotted a similar problem. The ImageList renders a <ul> tag in DOM. Hence I created my own ImageList styled <ul> component which works fine with ImageListItem. Here as per the gridTemplateColumns attribute for screens with display size sm will show 2 images, display size md will show 4 images
and display size lg will show 5 images.
import * as React from 'react';
import ImageListItem from '#mui/material/ImageListItem';
import { styled } from '#mui/material/styles';
const ImageGalleryList = styled('ul')(({ theme }) => ({
display: 'grid',
padding: 0,
margin: theme.spacing(0, 4),
gap: 8,
[theme.breakpoints.up('sm')]: {
gridTemplateColumns: 'repeat(2, 1fr)'
},
[theme.breakpoints.up('md')]: {
gridTemplateColumns: 'repeat(4, 1fr)'
},
[theme.breakpoints.up('lg')]: {
gridTemplateColumns: 'repeat(5, 1fr)'
},
}));
export default function ImageGallery({imageData}) {
return (
<ImageGalleryList>
{itemData.map((item) => (
<ImageListItem key={item.img}>
// Replace this with your ImageListItem
</ImageListItem>
))}
</ImageGalleryList>
);
}
This solution I came up with works, but seems like a lot of lines for something that Grid handles out of the box. Doesn't ImageList have some built in responsive design implementation?
export function Example(props) {
// not sure if there is a way to get something like this dictionary from React?
const breakpoints = {
xs: 0,
sm: 600,
md: 960,
lg: 1280,
xl: 1920
}
const getColumns = (width) => {
if (width < breakpoints.sm) {
return 2
} else if (width < breakpoints.md) {
return 3
} else if (width < breakpoints.lg) {
return 6
} else if (width < breakpoints.xl) {
return 7
} else {
return 8
}
}
const [columns, setColumns] = useState(getColumns(window.innerWidth))
const updateDimensions = () => {
setColumns(getColumns(window.innerWidth))
}
useEffect(() => {
window.addEventListener("resize", updateDimensions);
return () => window.removeEventListener("resize", updateDimensions);
}, []);
return (
<ImageList cols={columns}>
{/* list items ... */}
</ImageList>
)
}
Instead of using ImageList I used "Image masonry" seems to work.
https://mui.com/material-ui/react-masonry/#main-content
<Masonry columns={{ xs: 1, sm: 2, md: 3, lg: 4, xl: 5 }} spacing={{ xs: 1, sm: 2 }}>
Image masonry
This example demonstrates the use of Masonry for images. Masonry orders its children by row. If you'd like to order images by column, check out ImageList.
I resolved this by overriding column-count property on ImageList (root component)
So, you can add breakpoints using sx props
<ImageList
sx={{
columnCount: {
xs: '1 !important',
sm: '2 !important',
md: '3 !important',
lg: '4 !important',
xl: '5 !important',
},
}}
>
{/* list items ... */}
</ImageList>
Related
I'm new to react
I'm trying to figure out how I can make a Masonry image grid - mobile resonsive.
The idea is that I want the images to stack on top of each other on mobile view.
The Masonry grid should still act as a Masonry on desktop screens.
I just cannot figure out how to do that.
I appreciate the help.
Here is my code, view demo here
import * as React from 'react';
// material-ui
import { useTheme, styled } from '#mui/material/styles';
import { Box, Paper, Button, Container, Grid, Typography } from '#mui/material';
import Masonry from '#mui/lab/Masonry';
const Label = styled(Paper)(({ theme }) => ({
backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
...theme.typography.body2,
padding: theme.spacing(0.5),
textAlign: 'center',
color: theme.palette.text.secondary,
borderBottomLeftRadius: 0,
borderBottomRightRadius: 0,
}));
const MasonryPage = () => (
<Box>
<Masonry columns={3} spacing={3}>
{itemData.map((item, index) => (
<div key={index}>
<Label>{index + 1}</Label>
<img
src={`${item.img}?w=162&auto=format`}
srcSet={`${item.img}?w=162&auto=format&dpr=2 2x`}
alt={item.title}
loading="lazy"
style={{
borderBottomLeftRadius: 4,
borderBottomRightRadius: 4,
display: 'block',
width: '100%',
}}
/>
</div>
))}
</Masonry>
</Box>
);
export default MasonryPage;
const itemData = [
{
img: 'https://images.unsplash.com/photo-1518756131217-31eb79b20e8f',
title: 'Fern',
},
{
img: 'https://images.unsplash.com/photo-1627308595229-7830a5c91f9f',
title: 'Snacks',
},
{
img: 'https://images.unsplash.com/photo-1597645587822-e99fa5d45d25',
title: 'Mushrooms',
},
{
img: 'https://images.unsplash.com/photo-1529655683826-aba9b3e77383',
title: 'Tower',
},
{
img: 'https://images.unsplash.com/photo-1471357674240-e1a485acb3e1',
title: 'Sea star',
},
];
As the previous poster suggested you can use MUI's breakpoints to set the number of columns based on viewport width. For example:
import React from 'react';
import Masonry from '#mui/lab/Masonry';
import Box from '#mui/material/Box';
import Typography from '#mui/material/Typography';
const CollectionList = (props) => {
return (
<Box sx={{ pt: 4 }}>
<Typography variant="h2">Collections</Typography>
<Masonry columns={{ xs: 1, sm: 2, md: 3 }} spacing={2}>
<div>One</div>
<div>Two</div>
<div>Three</div>
</Masonry>
</Box>
);
};
export default CollectionList;
The value will be set implicitly for each breakpoint you specify as well as any up to the next one set. So in the example above, any viewport with medium (md) or higher will have 3 columns.
columns={{ xs: 1, md: 3, xl: 4 }}
would set 1 column for anything smaller than medium (md), 3 columns for anything larger or equal to medium up to extra large. From there on, it will be 4 columns.
you might want to try columns={{lg:3, md:6}} like this
I'm using Material UI datepicker in a React project. I've created a calendar + time selection (code below). For some reason when I test this on Chrome desktop using the device toolbar to emulate iphone 8 it works fine, but when I go to the site on my actual iphone 8, the UI is broken (images below). Any thoughts?
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Button, Typography } from '#material-ui/core';
import { makeStyles } from '#material-ui/core/styles';
import moment from 'moment';
import { MuiPickersUtilsProvider, DatePicker } from '#material-ui/pickers';
import DateFnsUtils from '#date-io/date-fns';
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
flexDirection: 'row',
padding: theme.spacing(3),
[theme.breakpoints.down('sm')]: {
padding: 0,
},
},
picker: {
display: 'flex',
flexDirection: 'row',
[theme.breakpoints.down('sm')]: {
flexDirection: 'column',
},
},
timeContainer: {
display: 'flex',
flexDirection: 'column',
marginLeft: theme.spacing(2),
overflowY: 'scroll',
[theme.breakpoints.down('sm')]: {
alignItems: 'center',
marginLeft: 0,
marginBottom: theme.spacing(3),
},
},
timeButton: { width: 226, height: 50 },
}));
export default function Timesgrid(props) {
const classes = useStyles();
const [selectedDate, setSeletedDate] = useState(moment());
const disableDay = date => {
const formattedDate = moment(date).format('YYYY-MM-DD');
return formattedDate in props.availability &&
props.availability[formattedDate].length > 0
? false
: true;
};
const handleDateChange = date => {
setSeletedDate(moment(date));
};
const renderTimes = () => {
const dateStr = moment(selectedDate).format('YYYY-MM-DD');
const availability = props.availability[dateStr];
return availability && availability.length ? (
<div className={classes.timeContainer}>
{availability.map((time, i) => (
<Button
style={{ marginTop: i === 0 ? 0 : 10 }}
key={time}
className={classes.timeButton}
variant="outlined"
color="primary"
onClick={() => props.onDatetimeSelected(moment(time))}
>
<b>{moment(time).format('LT')}</b>
</Button>
))}
</div>
) : (
<Typography variant="h6" className={classes.timeContainer}>
No availability
</Typography>
);
};
const renderPicker = () => {
return (
<div className={classes.picker}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DatePicker
disablePast
shouldDisableDate={disableDay}
variant="static"
defaultValue={selectedDate}
value={selectedDate}
onChange={handleDateChange}
/>
</MuiPickersUtilsProvider>
{renderTimes()}
</div>
);
};
return <div className={classes.root}>{renderPicker()}</div>;
}
Timesgrid.propTypes = {
availability: PropTypes.object.isRequired,
onDatetimeSelected: PropTypes.func.isRequired,
};
The answer to your question as we discussed in comments was to add the following CSS styling.
overflow: scroll
height: 100%
Justification:
The reason I suggested this solution was due to the comparisons in your images. The popup screen for the component was mushed together on the native browser popup but, not on the Chrome DevTools popup. This indicated that the native browser container was not allowing for overflow to occur.
Setting the height of the component to 100% ensures that it takes up the full height of it's container and allowing overflow ensures that if your component is greater than 100% of the containers height that it will render as shown in the devtools view.
Furthermore, In your reply you said your solution was
overflowY: scroll,
height: 100%
and overflow: scroll allows for overflow on both axes. Since the x-axis doesn't require overflow, this is a better solution.
Glad to see it worked.
I am trying to make material ui Chips scroll left and right in a single line.
Here is a code sandbox I am working on.
CodeSandbox
If I understood your question correctly...
What you want is basically a single line of material-ui chips with scrolling when the container size is not enough to show everything.
Demo code: Chips + overflow auto + maxWidth + flexWrap nowrap
It is somewhat easy to achieve this...
We can add overflow:auto and maxWidth:400px to the chips container element.
Basically, this tells the browser to show the scroll if the content requires more than 400px of horizontal space (width).
And to make the chips flow horizontally we just add to the container flexWrap: nowrap to instruct the render to do not wrap elements.
Sources:
Github: material-ui - docs/src/pages/components/chips/ChipsArray.js
You can certainly check out react-material-ui-caraousel.
Just like:
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import Chip from "#material-ui/core/Chip";
import Paper from "#material-ui/core/Paper";
import Carousel from 'react-material-ui-carousel'
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
justifyContent: "center",
flexWrap: "wrap",
listStyle: "none",
padding: theme.spacing(0.5),
margin: 0,
maxWidth: "1000px"
},
chip: {
margin: theme.spacing(0.5)
}
}));
export default function ChipsArray() {
const classes = useStyles();
const [chipData, setChipData] = React.useState([
{ key: 0, label: "Angular" },
{ key: 1, label: "jQuery" },
{ key: 2, label: "Polymer" },
{ key: 3, label: "React" },
{ key: 4, label: "Php" },
{ key: 4, label: "Golang" },
{ key: 4, label: "More" }
]);
const handleDelete = (chipToDelete) => () => {
setChipData((chips) =>
chips.filter((chip) => chip.key !== chipToDelete.key)
);
};
return (
<Paper component="ul" className={classes.root}>
<Carousel
autoPlay={false}
interval={0}
animation="slide"
timeout={100}
>
{
chipData.map( (item, i) => (
<li key={item.key}>
<Chip
label={item.label}
onDelete={handleDelete(item)}
className={classes.chip}
/>
</li>
) )
}
</Carousel>
</Paper>
);
}
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 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>
);
}