Home > Enterprise >  How to give conditional style to MUI TextField?
How to give conditional style to MUI TextField?

Time:12-24

I have created custom MUI TextField

const CustomDisableInput = styled(TextField)(() => ({
    ".MuiInputBase-input.Mui-disabled": {
        WebkitTextFillColor: "#000",
        color: "#000",
    },

    input: {
        "&[type=number]": {
            "-moz-appearance": "textfield",
        },
        "&::-webkit-outer-spin-button": {
            "-webkit-appearance": "none",
            margin: 0,
        },
        "&::-webkit-inner-spin-button": {
            "-webkit-appearance": "none",
            margin: 0,
        },
    },
}));

     <CustomDisableInput
       fullWidth
       variant="standard"
       size="small"
       type="text"
       sx={{
       backgroundColor: "grey.300",
       borderRadius: "3px",
       paddingX: "3px",
       }}
       InputProps={{
       disableUnderline: true,
       }}
       disabled={!isEditMode}
       />

now I want to apply

 sx={{ backgroundColor: "grey.300",borderRadius: "3px",paddingX: "3px"}}

only when isEditMode is true.

What i tried ?

 <CustomDisableInput
       fullWidth
       variant="standard"
       size="small"
       type="text"
       sx={ isEditMode && {
       backgroundColor: "grey.300",
       borderRadius: "3px",
       paddingX: "3px",
       }}
       InputProps={{
       disableUnderline: true,
       }}
       disabled={!isEditMode}
       />

but it gives error

Type 'false | { backgroundColor: "grey.300"; borderRadius: string; paddingX: string; }' is not assignable to type 'SxProps<Theme> | undefined'.
  Type 'false' is not assignable to type 'SxProps<Theme> | undefined'.  TS2322

CodePudding user response:

...
       sx={isEditMode ? {
         backgroundColor: "grey.300",
         borderRadius: "3px",
         paddingX: "3px",
       } : {}}

or

const CustomDisableInput = styled(({ isEditMode, ...props }) => (
  <TextField {...props} />
))(({ theme, isEditMode }) => ({
    ".MuiInputBase-input.Mui-disabled": {
        WebkitTextFillColor: "#000",
        color: "#000",
    },

    input: {
        "&[type=number]": {
            "-moz-appearance": "textfield",
        },
        "&::-webkit-outer-spin-button": {
            "-webkit-appearance": "none",
            margin: 0,
        },
        "&::-webkit-inner-spin-button": {
            "-webkit-appearance": "none",
            margin: 0,
        },
    },
    ...isEditMode && {
         backgroundColor: "grey.300",
         borderRadius: "3px",
         paddingX: "3px",
       }
}));
  • Related