Wannes
Wannes

Reputation: 1069

Change the color of a TextInput placeholder with Styled Components in React Native

How do you set the color of TextInput its placeholder with Styled Components in React Native?

I tried the following without any luck:

1.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   ::placeholder {
       color: green;
   }
`

2.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   &::placeholder {
       color: green;
   }
`

Upvotes: 12

Views: 35722

Answers (6)

douglasrcjames
douglasrcjames

Reputation: 1645

Not sure why this answer is so outdated, but none of these worked for me, it was as simple as this:

export const SearchInput = styled.input<MTStyledProps>`
    
    &::placeholder {
        color: ${onlyTheme.color.lightGrey};
    }

`;

Upvotes: 2

specify_
specify_

Reputation: 61

Adding on to @Fernando Pascoal Gomes's answer, if you wish to access the theme object, consider passing a function to .attrs() that returns an object that the component inherits for its props.

For your case, TextInput accepts a placeholderTextColor prop, so it might look like this:

const Input = styled.TextInput.attrs((props) => ({
  placeholderTextColor: props.theme.palette.placeholderColor,
}))`
  background-color: #fff;
  color: #000;
  ...
`

Upvotes: 6

Muhammed Moussa
Muhammed Moussa

Reputation: 5195

you can try:

export const NewTodo = styled.input`
  padding: 16px 16px 16px 60px;
  font-weight: 300;
  font-size: 15px;
  ::placeholder,
  ::-webkit-input-placeholder {
    color: red;
  }
  :-ms-input-placeholder {
     color: red;
  }
`;

How do I style an input placeholder with Styled Components?

Upvotes: 9

Fernando Pascoal Gomes
Fernando Pascoal Gomes

Reputation: 180

The best way to make this:

export const Input = styled.TextInput.attrs({
  placeholderTextColor: "red"
})`
  background-color: "#000";
`;

Upvotes: 16

Tim
Tim

Reputation: 10709

You cannot style the placeholder color with styled-components directly, but you can pass the placeholderTextColor property to your styled Textinput.

Example:

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

`

and then inside your render function:

<Input placeholder="hello" placeholderTextColor="green" />

Output:

output

Working example:

https://snack.expo.io/rybp-nKaE

Upvotes: 4

Pramod
Pramod

Reputation: 1940

To change the textinputs placeholder's text color user prperty "placeholderTextColor" eg

<TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        placeholder = 'Enter text'
        placeholderTextColor = 'red'
        value={this.state.text}
      />

Upvotes: 0

Related Questions