MUI options - The specified type 'string' cannot be matched with type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'

Is it possible to utilize custom variants in MUI v5? I am having trouble using a custom variant according to their documentation: https://mui.com/material-ui/customization/theme-components/#creating-new-component-variants

declare module "@mui/material/Button" {
  interface ButtonPropsVariantOverrides {
    icon: true;
    iconOnly: true;
  }
}


const muiButton = {
  MuiButton: {
    variants: [
      {
        props: { variant: "icon" },
        style: {
          background: palette.primary.main,
        },
      },
    ],
  },
};

createTheme({
  components: {
     ...muiButton 
  }
})

ts-error

TS2322: Type '{ MuiButton: { styleOverrides: { root: { fontStyle: string; fontSize: number; fontWeight: number; color: string; minWidth: string; borderRadius: number; "text-transform": string; boxShadow: string; "&.Mui-disabled": { ...; }; }; outlined: { ...; }; sizeSmall: { ...; }; sizeMedium: { ...; }; sizeLarge: { ...; }; }; v...' is not assignable to type 'Components<BaseTheme>'.   The types of 'MuiButton.variants' are incompatible between these types.     Type '({ props: { variant: string; size?: undefined; }; style: { background: string; color: string; "& .MuiSvgIcon-root": { height: number; }; "&.MuiButton-icon": { paddingRight: number; paddingLeft: number; }; ... 8 more ...; "&.Mui-disabled": { ...; }; }; } | { ...; } | { ...; } | { ...; })[]' is not assignable to type '{ props: Partial<ButtonProps<"button", {}>>; style: Interpolation<{ theme: Theme; }>; }[]'.       Type '{ props: { variant: string; size?: undefined; }; style: { background: string; color: string; "& .MuiSvgIcon-root": { height: number; }; "&.MuiButton-icon": { paddingRight: number; paddingLeft: number; }; ... 8 more ...; "&.Mui-disabled": { ...; }; }; } | { ...; } | { ...; } | { ...; }' is not assignable to type '{ props: Partial<ButtonProps<"button", {}>>; style: Interpolation<{ theme: Theme; }>; }'.   ...

Type 'string' is not assignable to type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'.

https://i.sstatic.net/ehoJe.png

Answer №1

You must narrow down the props.variant to a specific type, using just string is too general and MUI cannot process it in this context.

Try doing this:

props: { variant: "icon" as const }

... or this:

props: { variant: "icon" } as const

... or this:

import { ButtonProps } from "@mui/material"
props: { variant: "icon" } as ButtonProps

Answer №2

If you are currently utilizing createTheme and it is typed correctly, you have the option to directly include the definition of MuiButton within the call itself, instead of using the muiButton object:

createTheme({
  components: {
    MuiButton: {
      variants: [
        {
          props: { variant: "icon" },
          style: {
            background: palette.primary.main,
          },
        },
      ],
    },
  }
})

Give it a try.

This approach makes props.variant implicitly typed and ensures there are no compiler errors.

Answer №3

To tackle this problem, there are two possible solutions. The first option is to avoid using a constant muibutton and simply destruct it within Your createTheme function. Alternatively, if you prefer using a constant outside of createTheme, you must create a custom type or interface for muibutton where the variant is not just a type 'string', but rather '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'. This typing is necessary because in your `const muibutton ...``variant`, it is currently typed as string.

Edit: I've also come across discussions regarding the use of as const, which is another valid approach. An example of how to implement this would be:

props: { variant: "icon", color: "primary", size:'small' } as const,

If any part of this explanation is unclear, please let me know so I can provide further clarification.

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

"When the value is false, use the Vue binding to apply a specific

My challenge involves managing a website that is designed to receive boolean values and store them in an array where the key represents the ID and the value represents the boolean. For example: policiesActive[ "2" => false, "3" => false] The w ...

Tips for removing ASP.NET MVC controller name from angular route

My ASP.NET MVC login page leads to a different page that is integrated with Angular. After logging in, the URL looks something like this: http://localhost:5083/Home#/home I want to remove the ASP MVC controller name ("Home") from the URL. Is there a ...

Converting RGBA to Hex Color Code with Javascript: A Step-by-Step Guide

I attempted to change the rgba color representation to hexadecimal, but I encountered difficulty in converting the opacity value while successfully converting the remaining colors. Here is the snippet of my code: var colorcode = "rgba(0, 0, 0, 0.74)"; ...

Exploring the Contrasts: AppBar vs Toolbar in MUI v5

Can you explain the variations between AppBar and Toolbar in MUI? I know that AppBar defaults to 'column' flex direction, while Toolbar defaults to 'row'. Are there any other distinctions? Additionally, why do MUI docs show examples of ...

Failed to access the 'totalQty' property as it is undefined

I have developed a cart object that can hold products in a shopping cart. The issue arises when an item is undefined before it gets added to the cart. How can I ensure that the cart is defined even when it's empty during the session? I am using ejs. ...

The error message states that the type '{}' does not contain the property 'API_BASE_URL'

Encountering this error message when trying to access my API_URL as defined in the enviroment.ts file within a service class. Error: src/app/product/product.service.ts:12:25 - error TS2339: Property 'API_BASE_URL' does not exist on type '{} ...

Is it possible to utilize the `.apply()` function on the emit method within EventEmitter?

Attempting to accomplish the following task... EventEmitter = require('events').EventEmitter events = new EventEmitter() events.emit.apply(null, ['eventname', 'arg1', 'arg2', 'arg3']) However, it is ...

What is the best way to retrieve information from an array containing objects in AngularJS?

Check out this json data: { topalbums: { album: [ { name: "The Very Best of Cher", playcount: 1634402, mbid: "a7e2dad7-e733-4bee-9db1-b31e3183eaf5", url: "http://www.last.fm/music/Cher/The+Very+Bes ...

Module 'BrowserFetcher.js' could not be located

After updating all my npm packages, I encountered an issue when trying to run on my local server. The error message reads: Error: Cannot find module './BrowserFetcher.js' This error specifically points to a line in my puppeteer file located at - ...

Automatically select a value in MUI AutoComplete and retrieve the corresponding object

I recently set up a list using the MUI (v4) Select component. I've received a feature request to make this list searchable due to its extensive length. Unfortunately, it appears that the only option within MUI library for this functionality is the Au ...

Properly setting up event handling for a file input and Material UI Button

In my attempt to create a customized form using material UI elements, I am facing an issue. The form allows users to upload files and add notes for each option, which are stored in an array in the component's state. Here is a simplified version of th ...

Steps to Create an HTML Text Box that cannot be clicked

Does anyone know of a way to prevent a text box from being clicked without disabling it or blocking mouse hover events? I can't disable the text box because that would interfere with my jQuery tool tips, and blocking mouse hover events is not an opti ...

Issue with Date generation in TypeScript class causing incorrect date output

I have a simple code snippet where I am creating a new Date object: var currentDate = new Date(); After running this code, the output value is: Sat May 11 2019 13:52:10 GMT-0400 (Eastern Daylight Time) {} ...

The alert box for model validation summary errors is deactivated when hidden using .hide() method

In my MVC web application form, there is an optional postcode finder. If there is no match for the entered postcode, I add a custom error message to the .validation-summary-errors section. After the error is fixed, I remove all instances of the postcode cl ...

Managing the result efficiently when asp.net mvc ModelState IsValid is false

My colleagues and I are currently working on a CRUD application using .net mvc4. The project involves rendering dynamic content through jQuery based on customer choices. One challenge we face is the need to create multiple hidden inputs to pass additional ...

Creating HTML code from a website by utilizing XML

As someone who is not a developer and doesn't have much knowledge about java, I am seeking advice on potential solutions to achieve the following. This web hosting service enables users to retrieve data from their XML spreadsheets and embed them anyw ...

JS and its dynamic color changes

A game has been developed using JavaScript and HTML. The game features a table with cells that are assigned IDs for toggling colors using an onClick function. The objective is simple: when a cell is clicked, all neighboring cells, including the clicked one ...

Destructuring and For of Loop in ES6: Capturing the first object only

Working with my react app, I have a specific object called 'topics' that I am looping through: const topics = [ {name: 'Mon', color: 'blue', id: 1}, {name: 'Tue', color: 'red', id: 2}, {name: 'W ...

There seems to be an issue with the performance of Google script .setFormula when used in conjunction with the

Hello everyone, I have written a script that inserts formulas in a specific range and set up a trigger for it to run between 01:00 and 02:00 AM. The purpose is to subscribe the values with the formulas and then paste the resulting values. However, I am fac ...

Using javascript to overlay and position many images over another image

I've searched extensively but haven't been able to find any relevant answers here. Currently, I am developing a hockey scoring chance tracker. My goal is to display an image of the hockey ice where users can click to mark their input. Each click ...