Guide to applying conditional styling to Material-UI TextField

After creating a custom MUI TextField, I implemented the following styling:

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, my goal is to apply the styling defined in:

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

only when the value of isEditMode is set to true.

What I attempted:

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

However, this implementation resulted in an error message:

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

Answer №1

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

or

const StyledInput = styled(({ isCustomMode, ...otherProps }) => (
  <TextField {...otherProps} />
))(({ theme, isCustomMode }) => ({
    ".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,
        },
    },
    ...isCustomMode && {
         backgroundColor: "grey.300",
         borderRadius: "3px",
         paddingX: "3px",
       }
}));

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

What is the best way to incorporate an SVG icon into the helper text created by Formik and Yup within Material UI components?

With the React form in my setup, I am utilizing Formik, Yup, and Material UI for forms and textfields: import { TextField } from '@material-ui/core'; This is specifically for the E-mail form. Upon blurring out of the field, it produces the foll ...

What is the best way to utilize a mask in an inline SVG that is compatible with Chrome browser?

I am looking to visually crop my element using an SVG shape that is defined within the same HTML file (inline SVG). Using clip-path works perfectly: div { width: 200px; height: 200px; background-color: red; clip-path: url("#c"); } <div> ...

Failed verification of C-Lang in React-Hardware/Particle

Currently, I am utilizing React, React Hardware ([https://github.com/iamdustan/react-hardware/]), and Johnny-Five along with the Particle Photon. The error stack displayed below is what pops up when executing my lib/app.js file: # Fatal error in ../deps/v ...

The combination of jQuery, using .load method in javascript to prevent scrolling up, making XMLHttpRequest requests, updating .innerHTML elements, and troubleshooting CSS/JS

While utilizing this code, CSS and Javascript are disabled (only HTML loads): function loadContent(limit) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status ...

Is there a way to enhance the height of Bootstrap combobox items? Can this be achieved?

Is it possible to improve the height of Bootstrap combobox item? How can I achieve that? 1 2 3 4 ...

Error in REACT Application: Unhandled TypeError - Unable to loop through this.props.flights as it is not a function

As I delve into learning React, I encountered an error in my program that relates to the title. Below is the snippet of code where the issue arises: class FlightRow extends React.Component{ handleClicke=(event)=>{ console.log('delete button f ...

Attempting to remove the npm-cache directory

Is it safe to delete the C:\Users\ASUS\AppData\Local\npm-cache directory containing npm-cache? What impact would deleting this directory have? ...

What methods can be used to test scss subclasses within an Angular environment?

Exploring different background colors in various environments is a task I want to undertake. The environments include bmw, audi, and vw, with each environment having its own unique background color. Need help writing an Angular test for this? How can I mod ...

Struggling to establish a stable MQTT connection with Next.js? Many users have encountered errors and faced unstable connections. Read on

Currently, I am developing a real-time web application using next.js 14 along with the App router. In this project, I have integrated an MQTT connection that utilizes Mosquito under the hood. To establish the connection to the broker, I am leveraging the m ...

Implementing Asynchronous context tracking within a Remix application utilizing Express as the server

Utilizing Remix with Express as the server, I aim to develop an Express middleware that establishes an async context to grant all downstream functions (especially those in the "backend" Remix code) access to this context within the scope of a single reques ...

React Native: Triggering a Parent Component Rerender from a Child Component Event

There are two components in my setup. Main Component : App.js Sub-component : Logitem.js The Main Component displays a list of Sub-components. Each Sub-component contains a text element that, when clicked, triggers a modal display. The modal comprises ...

What is the proper way to invoke a variable-function in Node.js?

I have a function called `findPeopleByName` that queries the database for a specific username, but I'm not sure how to call it in my Node.js code. Here's what I have so far: // Retrieve user_name from POST request. app.post("/api/exercise/new-u ...

evt.target consistently returns the initial input within the list of inputs

My React file uploader allows users to attach multiple file attachments. Each time a user clicks on an input, I retrieve the data-index to identify the input position. renderFileUploader() { let file_attachment = this.state.file_attachment.map(fun ...

Is it advisable to use only one base SCSS @use import throughout the entire React application?

Hey there, I've got a question that's been on my mind. I really enjoy using SCSS in React, but for the longest time, I steered clear of variables and mixins because dealing with imports after making changes was a complete nightmare for me (I had ...

Is there a way to postpone the action so that the bot will not acknowledge the second command until after I have completed the first command

client.on('message', async (message) => { let author = message.author.username if (message.author.bot) return; if (message.content.startsWith('-queue open ')) { message.content = message.content.replace('-queue o ...

Using gradient colors for the background on the ::selection pseudo-element

Can you apply a gradient color to CSS ::selection? I tried using the following code: ::selection { background-image: -webkit-linear-gradient(left, #ee4037 0%, #eb297b 100%); } However, it did not have the desired effect. ...

How can I retrieve data from async/await functions in Node.js?

Recently, I attempted to incorporate async/await functionalities into my code. However, I encountered an issue with a specific async function that needed to return data from multiple nested await functions. The last await function involved a find query i ...

Setting nodeIntegration to false led to an Uncaught ReferenceError: require is not defined when trying to access Object.url (external "url":1) in the electron-react-typescript environment

After setting nodeIntegration to false, I encountered the following error message: "Uncaught ReferenceError: require is not defined at Object.url (external 'url': 1)". Upon clicking on the link referring to "external 'url': 1", it led ...

npm is notorious for not functioning on the current node.js version installed on my system. However, I am utilizing a version that it claims to be compatible with based on the error message

My current goal is to update node and npm to a newer version. The installed node version is 18.3.0, confirmed by running: <test> node --version v18.3.0 However, I encounter an issue when trying to use npm. It gives an error stating it cannot run on ...

Unusual addition symbols in the Bootstrap stylesheet

Something unusual is occurring in my bootstrap css code. I am noticing strange plus signs that seem out of place, and I cannot pinpoint a reason for their existence. Here's an example (you might need to enlarge the view as they are quite small): Thi ...