26

When using ordinary CSS if you want to style your place holder you use these css selectors :

::-webkit-input-placeholder {
    color: red;
}

But I can't figure out how to apply these type of styles in react inline styles.

8 Answers 8

15

Simply give your "input" tag an "id" or a "class" and put your css style in App.css inside src. e.g

//App.css or external stylesheet

#inputID::placeholder {
    color: #ff0000;
    opacity: 1;
}

//your jsx code
<input type="text" id="inputID" placeholder="Your text here" />

That actually worked for me.

Sign up to request clarification or add additional context in comments.

1 Comment

This isn't any different from what the OP already did. He is asking how to do this with inline HTML
10

You can't use ::-webkit-inline-placeholder inline.

It is a pseudo-element that (much like e.g. :hover) can only be used in your stylesheet:

The non-standard proprietary ::-webkit-input-placeholder pseudo-element represents the placeholder text of a form element.

Source

Instead, assign a class to the React component via the className property and apply the style to this class.

1 Comment

Alternative method for using pseudo-element without creating css file. Check this answer - stackoverflow.com/a/70480538/9282474
4

You could try to use radium

var Radium = require('radium');
var React = require('react');
var color = require('color');

@Radium
class Button extends React.Component {
  static propTypes = {
    kind: React.PropTypes.oneOf(['primary', 'warning']).isRequired
  };

  render() {
    // Radium extends the style attribute to accept an array. It will merge
    // the styles in order. We use this feature here to apply the primary
    // or warning styles depending on the value of the `kind` prop. Since its
    // all just JavaScript, you can use whatever logic you want to decide which
    // styles are applied (props, state, context, etc).
    return (
      <button
        style={[
          styles.base,
          styles[this.props.kind]
        ]}>
        {this.props.children}
      </button>
    );
  }
}

// You can create your style objects dynamically or share them for
// every instance of the component.
var styles = {
  base: {
    color: '#fff',

    // Adding interactive state couldn't be easier! Add a special key to your
    // style object (:hover, :focus, :active, or @media) with the additional rules.
    ':hover': {
      background: color('#0074d9').lighten(0.2).hexString()
    },
    '::-webkit-input-placeholder' {
        color: red;
    }
  },

  primary: {
    background: '#0074D9'
  },

  warning: {
    background: '#FF4136'
  }
};

3 Comments

this does not work for me. btw, you're missing a : on your '::-webkit-input-placeholder' json object
No need to use radium package. You can do this without doing it. Check this answer - stackoverflow.com/questions/70471012/…
why do we need a package to do a simple thing?
3

Do not use ::-webkit-inline-placeholder inline and Radium for one placeholder.

I suggest go to your index.css

input.yourclassname::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
  color: white;
  opacity: 1; /* Firefox */
}

Comments

2

My approach is to simply apply different styles to the entire <input /> component based on whether or not the value is empty. No need to install a new dependency, and no need to use a stylesheet which seems to be the point of the original question.

var inputStyles = {
    border: '1px solid #cbcbcb',
    color: '#525252',
};
var placeholderStyles = {
    ...inputStyles,
    color: '#999999',
};
<input
    type="text"
    placeholder="enter text here"
    value={myValue}
    style={myValue ? inputStyles : placeholderStyles}
/>

2 Comments

But the color style doesn't change the input placeholder's color...
@Yairopro, this example worked for me at the time I posted this. I would cite these resources which seem to corroborate that the color property is correct: developer.mozilla.org/en-US/docs/Web/CSS/::placeholder and css-tricks.com/almanac/selectors/p/placeholder
0

For me, I use Radium's Style component. Here's what you can do in ES6 syntax:

import React, { Component } from 'react'
import Radium, { Style } from 'radium'

class Form extends Component {
   render() {
      return (<div>
         <Style scopeSelector='.myClass' rules={{
            '::-webkit-input-placeholder': {
               color: '#929498'
            }}} />
         <input className='myClass' type='text' placeholder='type here' />
      </div>
   }
}

export default Radium(Form)

1 Comment

0

Use Template Literals i.e. Backward quotes(``) for adding your pseudo-element.

const inputFieldStyle = `
           .inputField::-webkit-input-placeholder{
                   color: red;
           }`

Using class is important thing so make sure you used class before pseudo-element.

Then you can use tag where you pass above style like below:

const reactFunctionalComponent = (props) => {
  ...
  return(
    <>
      <style>
        {inputFieldStyle}
      </style>
    ...
    </>
  )
}

Comments

0

Here is a method that provides pseudo selector functionality in React, without relying on a third party library, in about 20 lines of code.

This is an extension of RohitSawai's answer that injects a <style> tag, but in a more encapsulated and reusable fashion.

Define this function once in your project:

/** Returns a unique className and injectStyle function that can be used to 
style pseudo elements. Apply the className to the desired element and render 
injectStyle() nearby. The pseudo selector, e.g. ::-webkit-input-placeholder, 
will be appended to the unique className, styling a pseudo element directly, 
or a descendant pseudo element, as determined by the selector. */
const pseudo = (pseudoSelector, style) => {
  const className = `pseudo-${Math.floor(Math.random() * 1000000)}`

  // simple encoding of style dictionary to CSS
  // for simplicity, assumes that keys are already in slug case and units have 
  // been added, unlike React.CSSProperties
  const styleCSS =
    '{' +
    Object.entries(style)
      .map(([name, value]) => `${name}: ${value};`)
      .join('') +
    '}'

  return {
    className,
    injectStyle: () => (
      <style>
        {`.${className}${pseudoSelector} ${styleCSS}`}
      </style>
    )
  }
}

And use it like this:

const MyComponent = () => {
  const placeholder = pseudo('::-webkit-input-placeholder', { color: 'red' })

  return (<div>
    {placeholder.injectStyle()}
    <input className={placeholder.className} placeholder="This placeholder is red" />
  </div>)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.