Ask Your Question
2

What is the procedure for defining the type of prop used in the styled component of material UI?

asked 2023-02-17 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-11-29 01:00:00 +0000

lakamha gravatar image

To define the type of prop used in the styled component of material UI, you can use TypeScript (if it is already set up in your project) and define the prop type in the component interface. Here's an example:

import { styled } from '@mui/material/styles';

interface ButtonProps {
  variant: 'contained' | 'outlined';
  color?: 'primary' | 'secondary';
  size?: 'small' | 'medium' | 'large';
}

const Button = styled('button')<ButtonProps>(
  ({ theme, variant, color, size }) => ({
    color: theme.palette[color || 'primary'].contrastText,
    backgroundColor: theme.palette[color || 'primary'][variant],
    padding: theme.spacing(1, 2),
    fontSize: size === 'small' ? 14 : (size === 'medium' ? 16 : 18),
    // additional styles ...
  })
);

export default Button;

In the above example, we define the ButtonProps interface which has variant, color, and size properties, each with a specific set of possible values. Then, we pass this interface as a type parameter to the styled method and use it in the component function as a parameter. This allows us to access the properties in the theme object and apply different styles based on their values.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-02-17 11:00:00 +0000

Seen: 13 times

Last updated: Nov 29 '22