Encountering a TypeScript error in MUI 5 when attempting to spread values in props

I am encountering an issue with a typescript error related to the MUI sx prop. The problem arises when I attempt to merge or spread multiple sx values into an sx prop, resulting in an error. It seems to work fine if only one item is present in the sx prop, and it also works when spreading a single item within the sx prop. However, any attempts to include more than one item trigger the error.

Here is the error message:

No overload matches this call.
  Overload 1 of 2, '(props: { component: ElementType<any>; } & SystemProps<Theme> & { children?: ReactNode; component?: ElementType<any> | undefined; ref?: Ref<...> | undefined; sx?: SxProps<...> | undefined; } & CommonProps & Omit<...>): Element', gave the following error.
    Type '{} | { clipPath?: SystemStyleObject<Theme> | ResponsiveStyleValue<ClipPath | ClipPath[] | undefined> | ((theme: Theme) => ResponsiveStyleValue<...>); ... 810 more ...; displayPrint?: SystemStyleObject<...> | ... 1 more ... | ((theme: Theme) => ResponsiveStyleValue<...>); } | ... 33 more ... | { ...; }' is not assignable to type 'SxProps<Theme> | undefined'.
      Type '{ clipPath?: SystemStyleObject<Theme> | ResponsiveStyleValue<Property.ClipPath | Property.ClipPath[] | undefined> | ((theme: Theme) => ResponsiveStyleValue<...>); ... 843 more ...; [Symbol.unscopables](): { ...; }; }' is not assignable to type 'SxProps<Theme> | undefined'.
        Type '{ clipPath?: SystemStyleObject<Theme> | ResponsiveStyleValue<Property.ClipPath | Property.ClipPath[] | undefined> | ((theme: Theme) => ResponsiveStyleValue<...>); ... 843 more ...; [Symbol.unscopables](): { ...; }; }' is not assignable to type 'undefined'.
  Overload 2 of 2, '(props: DefaultComponentProps<BoxTypeMap<{}, "div">>): Element', gave the following error.
    Type '{} | { clipPath?: SystemStyleObject<Theme> | ResponsiveStyleValue<ClipPath | ClipPath[] | undefined> | ((theme: Theme) => ResponsiveStyleValue<...>); ... 810 more ...; displayPrint?: SystemStyleObject<...> | ... 1 more ... | ((theme: Theme) => ResponsiveStyleValue<...>); } | ... 33 more ... | { ...; }' is not assignable to type 'SxProps<Theme> | undefined'.
      Type '{ clipPath?: SystemStyleObject<Theme> | ResponsiveStyleValue<Property.ClipPath | Property.ClipPath[] | undefined> | ((theme: Theme) => ResponsiveStyleValue<...>); ... 843 more ...; [Symbol.unscopables](): { ...; }; }' is not assignable to type 'SxProps<Theme> | undefined'.
        Type '{ clipPath?: SystemStyleObject<Theme> | ResponsiveStyleValue<Property.ClipPath | Property.ClipPath[] | undefined> | ((theme: Theme) => ResponsiveStyleValue<...>); ... 843 more ...; [Symbol.unscopables](): { ...; }; }' is not assignable to type 'undefined'.ts(2769)
Box.d.ts(11, 7): The expected type comes from property 'sx' which is declared here on type 'IntrinsicAttributes & { component: ElementType<any>; } & SystemProps<Theme> & { children?: ReactNode; component?: ElementType<...> | undefined; ref?: Ref<...> | undefined; sx?: SxProps<...> | undefined; } & CommonProps & Omit<...>'
Box.d.ts(11, 7): The expected type comes from property 'sx' which is declared here on type 'IntrinsicAttributes & SystemProps<Theme> & { children?: ReactNode; component?: ElementType<any> | undefined; ref?: Ref<...> | undefined; sx?: SxProps<...> | undefined; } & CommonProps & Omit<...>'

Code snippet:

<Box sx={{ ...formElementHolderStyled, ...formGroupStyled }}>
  <FormElements cardID={cardID} config={edit} />
</Box>

SX values used:

export const formGroupStyled: SxProps<Theme> = {
  flexDirection: 'row',
  alignItems: 'flex-start',
  width: 1,
  pb: 3,

  '&:last-child': {
    pb: 0,
  },
};
export const formElementHolderStyled: SxProps<Theme> = {
  display: 'inline-flex',
  flexBasis: 370,
  '.MuiFormControl-root': { width: 1 },
};

Answer №1

It seems like this solution is effective https://mui.com/system/the-sx-prop/#passing-sx-prop

<Box sx={[
  ...(Array.isArray(formElementHolderStyled)
    ? formElementHolderStyled
    : [formElementHolderStyled]
  ),
  ...(Array.isArray(formGroupStyled)
    ? formGroupStyled
    : [formGroupStyled]
  )
]}>
  <FormElements cardID={cardID} config={edit} />
</Box>

Answer №2

The original poster's solution seems like a good approach.

Alternatively, you can convert the spread `sx` object to type `SxProps<Theme>` by using the following:

<Box sx={{ ...formElementHolderStyled, ...formGroupStyled } as SxProps<Theme>}>
  <FormElements cardID={cardID} config={edit} />
</Box>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an issue while trying to establish a page in material ui datagrid

My issue involves a table created using Material UI DataGrid. Whenever I navigate to the next page (2 or 3) and then apply a filter, the page remains at (2 or 3), leading to empty results as the filter is applied on the current page without filtering. I wa ...

Exploring Angular's APP_INITIALIZER: Comparing Promises and Observables

I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: initializeSettings, deps: [SettingsService], ...

Error message: Typescript and Styled-Component conflict: GlobalStylesProps does not share any properties with type { theme?: DefaultTheme | undefined; }

I've encountered an issue while passing props inside GlobalStyles in the preview.js file of my storybook. The props successfully remove the background from the default theme, but I'm receiving an error from Typescript: The error message states " ...

Stop Material-UI InputLabel from shifting to the top left corner of the Select element

I've been struggling to implement a true Placeholder functionality for the Material-UI Select component. It seems that using the placeholder prop on `<Select />` isn't working as expected, and I'm having issues with passing it to the i ...

Trigger parent Component property change from Child Component in Angular2 (akin to $emit in AngularJS)

As I delve into teaching myself Angular2, I've encountered a practical issue that would have been easy to solve with AngularJS. Currently, I'm scouring examples to find a solution with Angular2. Within my top-level component named App, there&apos ...

What is the best way to retrieve the value from a Material UI textfield after hitting the enter key

Having trouble retrieving input values with the provided code. Attempted using onKeyUp, onKeyDown, and onKeyPress, but none of them returned the value as desired. Typically, I would use the onChange property to get the value, but it triggers for every ne ...

Leverage the theme.spacing method within the override property when customizing createMuiTheme

What is the best practice for utilizing theme spacing when configuring a theme using createMuiTheme? I have typically hardcoded these values in the past and haven't encountered any problems since my projects generally stick with the default theme spac ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

Dynamically setting the IMG SRC attribute with the base64 result of a FileReader for file input

Looking for a little guidance on something new, I'll keep it brief because I'm sure it's just some small detail I'm overlooking... Starting with an image like this, where currentImage is the initial existing image path; <img src="{ ...

Difficulties with Grid Layout in React Material Design UI

I've been working on a project and I'm using the Material UI Grid Component to create a specific layout, but no matter what I do, I just can't seem to get it right. The layout I'm aiming for in my Dialog looks like this: In this layou ...

Error: TypeORM entity import token is not recognized

Currently, I am facing a peculiar error while transpiling my TypeScript code to JavaScript using TypeORM. The error message that pops up is as follows: (function (exports, require, module, __filename, __dirname) { import { Entity, PrimaryGeneratedColumn, M ...

Add items to a separate array only if the material UI checkbox is selected

Exploring the world of React, I decided to create a simple todo app using React JS and Material UI. With separate components for user input (TodoInput.js) and rendering individual todos with checkboxes (TodoCards.js), I aim to display the total number of c ...

Error encountered during conversion to Typescript for select event and default value

When trying to set the defaultValue in a Select component, TSlint throws an error - Type 'string' is not assignable to type 'ChangeEvent<HTMLInputElement> | undefined - for the code snippet below: const App = () => { const [ mont ...

Most effective methods for validating API data

Currently, I am working on developing an api using nestjs. However, I am facing some confusion when it comes to data validation due to the plethora of options available. For instance, should I validate data at the route level using schema validation (like ...

Vue textarea not accepting null values

My current setup includes the following dependencies: - "vue": "3.2.26", - "vee-validate": "4.5.6", - "typescript": "4.5.4" While working on a textarea field in vue3, I encountered an issue Here's a snippet with vee-validate integration import { Fie ...

The Material UI React radio buttons have the ability to modify the value of previous buttons

I'm facing an issue with my Material UI React Stepper Component that contains a group of radio buttons. The problem is that changing the radio button in one step affects the selected value in previous and future steps. I've experimented with diff ...

Angular 6's observable variable doesn't properly support Ng If functionality

I successfully implemented server-side pagination in the Angular6 material data grid following the instructions from this link. Now, I am facing an issue where I want to display a "No Data Found" message if the response dataset is empty. I tried using ngI ...

Changing the global type in TypeScript

Currently, I am incorporating two third-party TypeScript libraries into my project. Interestingly, both of these libraries expose a global variable with the same name through the Window interface. However, they offer different methods for interacting with ...

Transforming Bootstrap using Typescript styled components

I have been working on customizing the Navbar in my React app using Typescript's styled components. However, I am facing difficulties in restyling the default styles from Bootstrap that I have copied. Here is an example of the React Bootstrap Navbar c ...

Guide to highlighting input field text using Angular

I've set up an angular page that includes an input field within its template. My goal is to highlight the text in the input field when a specific function is triggered. When I refer to "highlighting the text," I mean (check out the image below) https ...