Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to customize material-ui TextField Input underline:after?

I am using Material-ui for React.

I am trying to customize the color of the underline that transitions into place when the user clicks the Mui <TextField> component, which is a result of jss injecting the following CSS:

.MuiInput-underline:after {
    border-bottom: 2px solid #303f9f;
}

I am already invested into styled-components theme provider and do not want to bring in the MuiTheme provider in order to use createMuiTheme and override.

I have used styled-components to override styling for many other Mui components, but have been unable to override .MuiInput-underline:after using styled-components.

I am now trying to use Mui's withStyles, but am unsure of the exact style semantics. I've been unsuccessful using InputProps and using classes.

const styles = theme => ({
  inputProps: {
    underline: {
      '&:after': {
        border: '2px solid red'
      }
    }
  }
});

const MyTextField = props => {
  const { classes, ...rest } = props;

  return (
    <TextField InputProps={{ inputProps: classes.inputProps }} {...rest} />
  );
};

export default withStyles(styles)(MyTextField);

Any thoughts? Thanks.

like image 451
KenB Avatar asked Aug 22 '19 04:08

KenB


2 Answers

Here's an example of how to customize the underline using styled-components:

import TextField from "@material-ui/core/TextField";
import styled from "styled-components";

const StyledTextField = styled(TextField)`
  /* default */
  .MuiInput-underline:before {
    border-bottom: 2px solid green;
  }
  /* hover (double-ampersand needed for specificity reasons. */
  && .MuiInput-underline:hover:before {
    border-bottom: 2px solid lightblue;
  }
  /* focused */
  .MuiInput-underline:after {
    border-bottom: 2px solid red;
  }
`;

export default StyledTextField;

Edit TextField underline styled-components

Related answers:

  • How can I remove the underline of TextField from Material-UI?
  • How do I custom style the underline of Material-UI without using theme?
like image 180
Ryan Cogswell Avatar answered Nov 09 '22 18:11

Ryan Cogswell


You need to omit the inputProps key in styles object.
You also need to provide classses Prop to InputProps:

 const styles = theme => ({
    underline: {
      color: 'red' ,
      '&::after': {
        border: '2px solid red'
      }
    }
 });

 const MyTextField = props => {
   const { classes, ...rest } = props;
   return (
     <TextField InputProps={{ classes: {underline: classes.underline} }} {...rest} />
   );
 };

You can check this working code sandbox example: https://codesandbox.io/s/material-demo-75w7p?fontsize=14

like image 36
Ido Avatar answered Nov 09 '22 18:11

Ido