MUI and TypeScript: How to use !important?

Viewed 28516

I'm building a React application and I'm using MUI for my components. I wonder how I can give an !important property to a style?

I tried this:

<Paper className="left"...>

I'm using withStyles and WithStyles. Then in my styles.ts:

left: {
  display: "block",
  float: "left!important",
},

But this throws the error:

[ts] Type '"left!important"' is not assignable to type '"right" | "none" | "left" | "-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "inline-end" | "inline-start" | undefined'.
index.d.ts(1266, 3): The expected type comes from property 'float' which is declared here on type 'CSSProperties'
(property) StandardLonghandProperties<TLength = string | 0>.float?: "right" | "none" | "left" | "-moz-initial" | "inherit" | "initial" | "revert" | "unset" | "inline-end" | "inline-start" | undefined

How would one assign an !important flag when using material-ui with TypeScript?

4 Answers

You can just cast it. For example:

left: {
  display: "block",
  float: "left!important" as any,
},

or

left: {
  display: "block",
  float: "left!important" as "left",
},

Here's a playground example.

there are several ways to overstyle a MUI component. Simplest and straight forward is to apply a stlye on the component itself. an inline styled weights more specifity then the provided css. You would use it like this:

<Paper style={{display: 'block'}}...>

If you want to make use of normal CSS:

import './style.css'

and provide a class on the component

<Paper className="left"...>

By this you will be able to use normal css like

left: {
  display: "block",
  float: "left!important",
},

I really recommand to think about the specifity and what to achieve with your styles, before you implement them, otherwise you will start a fight against MUI styles and this can get pretty nasty. Hopefully this helps, happy coding ;-)

A cleaner way is to write a helper method:

function important<T>(value: T): T {
  return (value + ' !important') as any;
}
const MyComponent = styled('div')({
  fontWeight: important('bold'),
});

Codesandbox Demo

This seem to work for me

<Toolbar
        sx={{
          minHeight: '0 !important',
        }}
      />
Related