Styling the placeholder in a TextField

oligofren picture oligofren · Dec 14, 2017 · Viewed 40.3k times · Source

The TextField API doesn't mention anything about how one could style the pseudo placeholder element of the input element.

Basically, I would like to change the default styling of the placeholder text, and the normal bag of tricks doesn't work, as I cannot access the element.

Is there a way I can get to it? And if so, what is the JSS/React/DOM equivalent way of writing ::-webkit-input-placeholder?

Answer

Rafa picture Rafa · Jan 31, 2018

Case 1

Put the desired placeholder text in the label property of the TextField component, and use the labelClassName property of the TextField to customize it. You could also pass InputLabelProps with a className, classes or style attribute.

Case 2

Refrain from using the label property of TextField and put the placeholder text on its placeholder property instead. Leverage InputProps to override the generated HTML input element's class.

Code

The code below covers both aforementioned cases. CodeSandbox snippet.

import React from 'react';
import TextField from 'material-ui/TextField';
import { withStyles } from 'material-ui/styles';
import withRoot from '../components/withRoot';

const styles = {
  'input-label': {
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    width: '100%',
    color: 'red'
  },

  'input': {
    '&::placeholder': {
      textOverflow: 'ellipsis !important',
      color: 'blue'
    }
  }
};

class Index extends React.Component {
  render() {
    return <div style={ {width: 150, margin: '0 auto'} }>
      {/* Uses "label" and "labelClassName". */}
      <TextField
        fullWidth
        label='I am a really really long red TextField label'
        labelClassName={ this.props.classes['input-label'] } />

      {/* Uses "label" and "InputLabelProps" with inline styles. */}
      <TextField
        fullWidth
        label='I am a really really long green TextField label'
        InputLabelProps={{
          style: {
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            width: '100%',
            color: 'green'
          } }} />

      {/* Uses "placeholder" and "InputProps" with "classes". */}
      <TextField
        fullWidth
        margin='normal'
        placeholder='I am a really really long glue TextField label'
        InputProps={{ classes: {input: this.props.classes['input']} }} />
    </div>;
  }
}

export default withStyles(styles)(Index);

EDIT

The previous solutions are good if you'd like to personalize a specific component instance. To change the placeholder globally, see ninjaPixel's answer.