BugggyBug
BugggyBug

Reputation: 43

Set PlaceHolder color of a textarea dynamically in React

I'm trying to set the color of a placeholder inside a text-area which is my react component dynamically but failing to do so. I'm using CSS for styles where I set my default colors but these colors are updated later by the props. I'm able to set stuff like background-color, color etc easily but unable to set nested properties or pseudo selectors like ::placeholder. Any help is appreciated.

I've tried setting it using plain JS and a couple of other inline styling practices but failing.

<div className="container-textarea">
              <TextAreaWrapper
                placeholder="Write message"
                style={color: props.color }
                />        
        </div>

//In style props, the color is set dynamically but I want to set the color of that placeholder dynamically as well.

I've tried doing this

const styles = {
color : props.color,
'::placeholder' : {
color : props.color
}
}

Upvotes: 0

Views: 5361

Answers (1)

jcubic
jcubic

Reputation: 66590

If you use style attribute you can use selectors only css properties.

style="color: red"

But there is a way to make it work dynamically, what you need is CSS variables (real spec name are Custom Properties) so you put this CSS into your style file:

::-webkit-input-placeholder { /* Chrome/Opera/Safari */
  color: var(--placeholder-color);
}
::-moz-placeholder { /* Firefox 19+ */
  color: var(--placeholder-color);
}
::placeholder {
  color: var(--placeholder-color);
}

then you can use React to add:

    <div className="container-textarea">
          <TextAreaWrapper
            placeholder="Write message"
            style={'--placeholder-color': props.color }
            />        
    </div>

Also I'm not sure you don't need {{'--placeholder-color': props.color }} one curly braces are react prop value and one are JS object inside.

Upvotes: 2

Related Questions