Ordering styles in Material UI

I've spent countless hours customizing this element to perfection, but the more I work on it, the more of a headache it gives me.

The element in question is an outlined TextField, and my focus has been on styling its label and border. Initially, I thought using the sx prop for customization would be straightforward, but unfortunately, it did not produce the desired results.

const One = () => (
  <div>
    <TextField
      id="outlined-basic"
      label="One"
      variant="outlined"
      sx={{
        "& .MuiOutlinedInput-root": {
          borderRadius: 0,
        },

        "& .MuiInputLabel-root": {
          color: "orange",
        },

        "& .Mui-focused .MuiOutlinedInput-notchedOutline": {
          borderColor: "orange",
        },
      }}
    />
  </div>

My goal is to keep the label always orange and have the border turn orange when focused. However, when I focus on the TextField, both the label and border revert back to blue. The only style that sticks is the border-radius adjustment.

After inspecting the result, it appears that the default styles are reinserted when the component is focused. This is confusing to me because I anticipated these styles would have been applied initially, upon mounting the TextField. Why isn't the sx prop overriding the default styles?

https://i.sstatic.net/9EpXr.png

https://codesandbox.io/s/material-ui-customization-zg5v5v?file=/src/components/One.jsx

Answer №1

If you want to enhance the specificity of the focused class selector, simply include it in the root element.

const One = () => (
  <div>
    <TextField
      id="outlined-basic"
      label="One"
      variant="outlined"
      sx={{
        '& .MuiOutlinedInput-root': {
          borderRadius: 0,
        },

        '& .MuiInputLabel-root': {
          color: 'orange',
        },

        '&  .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline': {
          borderColor: 'orange',
        },
      }}
    />
  </div>
);

This should work effectively for your requirements!

Answer №2

Check out this code snippet that ensures the label always stays orange.

<TextField
  id="outlined-basic"
  label="One"
  variant="outlined"
  sx={{
    "& .MuiOutlinedInput-root .MuiOutlinedInput-notchedOutline": {
      borderColor: "black" // or your default/initial color
    },
    "& .MuiOutlinedInput-root:hover .MuiOutlinedInput-notchedOutline": {
      borderColor: "orange"
    },
    "& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline": {
      borderColor: "orange"
    },
    "& .MuiInputLabel-root": {
      color: "orange", // This is how you add the color to the label
      "&.Mui-focused": {
        color: "orange" // This is how you add the color to the label on focus
      }
    }
  }}
/>

Take a look at the modified version of this codesandbox for a hands-on experience.

Answer №3

To enhance your styling, consider nesting one style within another

https://codesandbox.io/s/material-ui-customization-forked-fgzg5g


<TextField
  id="outlined-basic"
  label="One"
  variant="outlined"
  sx={{
    "& .MuiOutlinedInput-root": {
      borderRadius: 0,
      "&.Mui-focused .MuiOutlinedInput-notchedOutline": {
        borderColor: "orange",
        color: "inherit"
      }
    },

    "& .MuiInputLabel-root": {
      color: "orange"
    }
  }}
/>;

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

Issues arise when setting a delay for CSS transitions to occur due to the

I'm trying to create a scroll bar that only appears when hovered over, similar to how it works on Facebook where the scroll bar shows up slowly instead of all at once. I've tried using CSS transition delay, but it doesn't seem to be working ...

Full-screen background with image adhering perfectly - left-aligned button that stays in place

Excuse me if my question seems basic, as I am just starting out in front-end development and may not know all the necessary terms to fully understand existing questions. I currently have a simple html file that consists of a title and three buttons, with ...

Tips for customizing the `src/app/layout.tsx` file in Next.js 13

I am looking to customize the layout for my /admin route and its child routes (including /admin/*). How can I modify the main layout only for the /admin/* routes? For example, I want the / and /profile routes to use the layout defined in src/app/layout.ts ...

Elevating state and retrieving data from a dynamically generated text input field

Within my Component, I am initiating a Modal where I pass a form in the following manner:- <Modal show={showGroupModal} onCancel={closeGroupModalHandler} header="Please add Group Name" contentClass="player-admin__modal-content&quo ...

AlignItems not functioning properly within a list component in NativeBase

My attempt to align the Thumbnail to the topLeft using justifyContent: 'flex-start' is not working as expected. Here's my code snippet: <Content> <View key = {index} style={styles.commentBody}> <List> <ListItem ...

Encountering an error message stating "The variable 'App' is declared but not used" when running the index.tsx function

This React project is my attempt to learn how to use a modal window. The tutorial I've been following on YouTube uses JavaScript instead of TypeScript for their React project. However, I'm facing some challenges. Could you possibly help me ident ...

Failure [ERR_STREAM_WRITE_AFTER_END]: writing past the endpoint [npm-request using socket.io]

My server has a socket server running, and on my laptop, I have a socket.io-client service. When both are turned on, they establish a connection. When other users request information from my server, the server sends that request to my laptop via a socket. ...

Managing form submissions using Jquery and checkboxes

Whenever I submit my dynamically created form, all checkboxes briefly become selected for a split second. Does anyone have an explanation for this behavior? Is it common or is there something wrong with my code? Although the form submits correctly, it migh ...

Error message: Redux-toolkit: The store does not contain a valid reducer

I've hit a roadblock with understanding how to integrate redux and next.js. Despite spending countless hours trying to connect the two, I keep encountering an error stating "TypeError: Cannot read property 'getState' of undefined". It seems ...

I am looking to transform CSV data into XLSX file format, upload it to AWS, and obtain the corresponding URL

I am currently in the process of converting a JSON file to CSV. My next step is to convert this CSV file to XLSX data and upload it to AWS to retrieve the link. Convert CSV to XLSX const xlsxFilePath = 'path/to/transaction_data.xlsx'; await csvto ...

Attempting to create an auto-suggestion tool that can process and accept multiple input values, filtering out only those that begin with a designated character

I've been working on implementing an auto-suggestion feature that displays suggestions with partial matches or values within the input box. The goal is for it to only provide suggestions that begin with a specific character, like the "@" symbol. Fo ...

The Formik Material UI Localization Provider is not functioning properly when paired with the Luxon Adapter for formatting dates in

Currently, I am utilizing the MUI localization provider in conjunction with the luxon adapter to transform the date format to GB. However, despite my efforts, the date remains in the mm/dd/yyyy format rather than displaying as dd/mm/yyyy. Please refer ...

The update of the attribute in jQuery on a checkbox is not causing the change event to trigger

I am working on a feature where there are multiple checkboxes along with a status box that indicates if at least one of the checkboxes is checked. Additionally, I have included a Check All/None checkbox that can toggle all the checkboxes. However, althoug ...

Customizing material-ui styles within a nested component

I am looking to modify the position of the expandIcon in an ExpansionPanel by changing the right attribute: <ExpansionPanel> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}&g ...

What is the best way to incorporate a gratitude note into a Modal Form while ensuring it is responsive?

Currently, I have successfully created a pop-up form, but there are two issues that need fixing. The form is not responsive. After filling/submission, the form redirects to a separate landing page for another fill out. Expected Outcome: Ideally, I would ...

implementing a smooth transition effect for image changes upon hover

I've been working on a React project where I created a card that changes its image when hovered over. I wanted to add a smoother transition effect to the image change using transition: opacity 0.25s ease-in-out;, but it doesn't seem to be working ...

What is the best way to specify the CSS :hover state within a jQuery selector?

I am trying to change the background color of a div element when hovered using jQuery, but for some reason the following code is not working as expected: $(".myclass:hover div").css("background-color","red"); Can someone provide guidance on how to achiev ...

Is it possible for third party packages to function properly without the node_modules directory?

Whenever we push our code to GitHub or any other remote repository service, we make sure to exclude the node_modules folder. This begs the question: how are all the third-party libraries functioning on the hosted website if the node_modules folder is not ...

Exploring the functionality of filtering cards using a search box in Bootstrap 5 and JavaScript

https://i.sstatic.net/VlD20.png I tried to bring the medicine I searched for to the top by clicking on the search button, but unfortunately it did not work. Can someone help me with writing the JavaScript code for this? <form class="form-inline ...

Tips for managing Express.js callbacks and modifying an object's property from within a function

I am currently working with two JavaScript files. I have successfully retrieved data from MongoDB using the method bookDao.getActiveBookByCategoryId(). The Issue I Am Facing: Within the categoryDao.js file, I am attempting to update the resultJson.book_c ...