Rohil
Rohil

Reputation: 75

Responsive prop value doesn't work in MUI v5

I'm trying to customize my button so when my site is on mobile view I want a small-sized button... & when my screen hits the MD breakpoint I want the button size to be 'large'

My current button styles : Current button styles

I tried doing size={{ xs: "small", md: "large" }} but it did not work

Please help.

Upvotes: 2

Views: 1295

Answers (2)

NearHuscarl
NearHuscarl

Reputation: 81643

size is not a valid property in sx prop. Only the properties inside sx support responsive values. If you want to assign a prop based on the current width, you need to write a custom hook:

import { Breakpoint, useTheme } from '@mui/material';

type ResponsiveValue<T> = {
  [P in Breakpoint]?: T;
};
function useResponsiveProp<PropValue>(
  responsiveValue: ResponsiveValue<PropValue>,
) {
  // you can copy the useWidth hook definition in the official docs:
  // https://mui.com/components/use-media-query/#migrating-from-withwidth
  const width = useWidth();
  const theme = useTheme();
  const keys: readonly Breakpoint[] = [...theme.breakpoints.keys];

  keys.reduce((lastNonNullValue, key) => {
    if (!responsiveValue[key]) {
      responsiveValue[key] = lastNonNullValue;
      return lastNonNullValue;
    }
    return responsiveValue[key];
  }, responsiveValue[keys[0]]);

  return responsiveValue[width];
}

Usage

import Button, { ButtonTypeMap } from '@mui/material/Button';

type ButtonSize = ButtonTypeMap['props']['size'];
const size = useResponsiveProp<ButtonSize>({
  xs: 'small',
  sm: 'medium',
  lg: 'large',
});

Live Demo

Codesandbox Demo

Upvotes: 0

Amine Belmahi
Amine Belmahi

Reputation: 121

According the MUI documentation, it says that the size prop in button component takes a string as a value ('small' or 'medium' or 'large') and therefore providing an object with different breakpoints should not be working.

In this case, I suggest to condition the size according to the window breakpoint

const [width, setWidth] = useState(window.innerWidth)

<Button size={width < 600 ? 'small' : 'large'}>
  More Details
</Button>

Upvotes: 1

Related Questions