ReactJS material-ui use the class `Mui-disabled` for read-only components

Viewed 11392

I'm building a new component from TextField and I need to apply the same style for text fields with the readOnly than disabled property.

So, I was trying to use the property className but it does not work.

// some logic here ..

<TextField
    {...props}
    className={readOnly ? 'Mui-disabled' : undefined}
 />

So, I also tried to use the classses prop, but I don't know how to get the current config from the disabled class.

3 Answers

When you use the disabled property, Material-UI places the Mui-disabled class on many different elements. To get the equivalent look, you need to add it to all the same elements.

Below is an example of how to do this. In addition to adding the Mui-disabled class, it is also necessary to override the "focused" styling of the underline (handled via the :after pseudo-class).

import React from "react";
import ReactDOM from "react-dom";

import TextField from "@material-ui/core/TextField";
import { makeStyles } from "@material-ui/core/styles";
const disabledClassNameProps = { className: "Mui-disabled" };
const useStyles = makeStyles(theme => {
  const light = theme.palette.type === "light";
  const bottomLineColor = light
    ? "rgba(0, 0, 0, 0.42)"
    : "rgba(255, 255, 255, 0.7)";
  return {
    underline: {
      "&.Mui-disabled:after": {
        borderBottom: `1px dotted ${bottomLineColor}`,
        transform: "scaleX(0)"
      }
    }
  };
});
function App() {
  const classes = useStyles();
  return (
    <div className="App">
      <TextField
        {...disabledClassNameProps}
        inputProps={{ readOnly: true }}
        InputProps={{ ...disabledClassNameProps, classes }}
        InputLabelProps={disabledClassNameProps}
        FormHelperTextProps={disabledClassNameProps}
        label="Test Disabled Look"
        defaultValue="Some Text"
        helperText="Helper Text"
      />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit TextField readOnly looking disabled

Related answers:

After some digging, I found that the InputProps also have the className property. The following worked for me:

<TextField
    {...props}
    inputProps={{
        readOnly,
    }}
    InputProps={{
        className: (readOnly) ? 'Mui-disabled' : undefined,
    }}
/>

To see all the properties you can look here.

You need to use classes on TextField

<TextField
 {...props}
 classes={readOnly ? { root: 'Mui-disabled' } : {}}
/>

Hope it helps

Related