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

Column-count can result in the flex div dividing the element into two parts

Whenever I utilize column-count with nested divs that have display: flex set, I encounter a problem where elements are cut in half. The suggestion from this answer is to use display: inline-block to prevent this issue. However, when I implement that soluti ...

What could be causing my NodeJS Backend to not retrieve the data properly?

For a current project, I am tasked with building a mobile application using Flutter for the frontend and NodeJS for the backend. To facilitate this, I have acquired a VPS from OVHcloud running Ubuntu 20.04. Following various tutorials, I set up a server as ...

Unable to forward page in EJS

Hey everyone, I've been struggling with trying to redirect to a page in EJS, but it just doesn't seem to work for some reason. Here's my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...

What methods can I employ to utilize CSS on a table row that contains a specific class in an HTML

Is there a way to make the CSS affect <tr class="header"> with the class of header? CSS table.table-bordered tr:hover{ background-color: #C0C0A9; } table.table-bordered tr { background-color: #C0C0D9; } Any suggestions on what I ...

Choose the span element within every other td that is not enclosed by an anchor tag

The table structure I am working with is as follows: <tr> <td> <a> <span> some content </span> </a> </td> <!-- td having straight span --> <td> <span> ...

Is it advisable to utilize React.FC for typing your Next.js components?

One of my favorite tools is the VScode extension called "React Typescript Snippets". It includes a snippet named tfcd that generates a function component base with Typescript and default export. import React from 'react'; type indexProps = { ...

Troubleshooting Issue with Jssor Slider in Internet Explorer 11 due to Relative Dimensions

Encountering an issue with the relative dimensions of the slider container in IE11 (Jssor 18.0). Here is the HTML structure: An outer div with specified absolute dimensions (width and height in pixels). An inner div, serving as the slider's contain ...

How require works in Node.js

My current database connection module looks like this: var mongodb = require("mongodb"); var client = mongodb.MongoClient; client.connect('mongodb://host:port/dbname', { auto_reconnect: true }, function(err, db) { if (err) { ...

Delayed execution not completely cancelled prior to component being unmounted

Alert: Avoid calling setState (or forceUpdate) on an unmounted component. While this won't cause any issues, it could suggest a memory problem in your application. Make sure to clean up all subscriptions and async tasks in the componentWillUnmount met ...

Steps to transfer extra files such as config/config.yaml to the .next directory

I have the following folder structure for my NextJS project: _posts/ components/ hooks/ config/ <--- includes config.yaml file for the server pages/ public/ .env.local ... yarn build successfully copies all dependencies except for the config/ folder. ...

Setting up button alignment in Bootstrap

In my current template, I am utilizing Bootstrap and need to position three buttons accordingly. The first button should be all the way to the left, the second in the middle, and the third (final) one on the right within a container element. While attempt ...

What are the best ways to implement co with express?

I've been using express in conjunction with node and I'm interested in implementing a co/yield pattern to manage my async callbacks efficiently. Currently, the code has this structure: web.post('/request/path', function(req, res, next ...

Sharing a unique JSON message on Slack via a webhook

Is there a way to send a custom JSON message with indentation using a Slack webhook in a Node.js app? var Slack = require('slack-node'); var JsonMessage = process.argv[2]; webhookUri = "https://hooks.slack.com/services/XXXX/xxxx/xxxxxxxx"; sla ...

Minimizing redundancy in React Redux application callbacks

Trying to grasp the concept of using react and redux together has been quite challenging for me. The issue I am facing is that as my app becomes more complex, it seems like there is a lot of repetitive code to deal with. For instance, let's consider ...

Unable to execute node packages installed globally

Recently, I installed nodejs on my computer and decided to globally install "http-server" using npm (npm install -g http-server). However, upon trying to run http-server, I encountered an error message stating that "'http-server' is not recognize ...

Securing Your Next.js Web App with Session Authentication

I have encountered a challenge while integrating NextAuth authentication into my React.js web application. To ensure seamless user authentication across the entire app, I am attempting to wrap a SessionProvider around the root component. However, VSCode ...

Checking the Length using JQuery

My dilemma is with a text field (datepicker) - I want the button to change color when someone selects a date, but it's not working. Can you please assist me? HTML <input type="text" id="datepicker"> <button type="button" onclick="" class=" ...

Tips for effectively utilizing a cart collection system

I am currently exploring how to utilize sessions for user tracking and updating my cart collection. Below is the code from my route.js file in an Express and Node application: app.post('/cart/:id', function (req, res) { if (!userKey) { ...

Troubleshooting Problem with Padding in ion-content for Ionic Angular

I am currently developing my inaugural Ionic application. The initial template I utilized was the rudimentary sidemenu layout. $ ionic start myApp sidemenu Afterwards, I crafted a straightforward page featuring a list which appears as follows... <ion ...

CSS background: seeking a fresh background for the rest of my pages

When I use CSS background: url(stuffhere.jpeg) for the background, it remains unchanged when clicking on other videos categorized as "projects," not pages. I have attempted using <body id="home"> and <body id="projects">, creating two backgrou ...