Reputation: 375
hi guys i want to change textcolor of input dynamically. for example initially in CSS placed as color:'#fff',then i want to change the text color whenever need as '#ddd'.
Upvotes: 1
Views: 6523
Reputation: 4259
Similar to Khushboo Shah's answer, this is how I adjusted the color for my Component
. The code must be placed in the render()
function, and render()
must be triggered using normal methods.
render() {
var overrideStyle = {};
if ( condition ) {
overrideStyle = { color: '#ddd' };
}
return (
<Text style={[ this.props.style, overrideStyle ]}>
//...
</Text>
);
}
Upvotes: -1
Reputation: 6223
I have created sample app from expo to demonstrate dynamic color changes. I have used interval, but you can use as per your need with setColor function.
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { Constants } from 'expo';
export default class App extends Component {
constructor() {
super();
this.state = { colors: '#ffffff' };
}
setColor = (value) => {
this.setState({ colors: value })
}
componentDidMount() {
let i = 0;
let colorsArray = ['gray', 'red', 'green', 'blue', 'pink', 'yellow']
this._interval = setInterval(() => {
if (i <= 5) {
this.setColor(colorsArray[i]);
i++;
}
}, 5000);
}
render() {
return (
<View style={styles.container}>
<Text style={{ color: this.state.colors }}>
Change code in the editor and watch it change on your phone!
Save to get a shareable url. You get a new url each time you save.
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
Upvotes: 0
Reputation: 80
You can use ternary operator
to check your condition. It has following format:
(test conditon) ? true statement: false statement
Based on that, you can set the <TextInput>
color
with something like this:
<TextInput
style={[styles.input, (this.state.username ? styles.inputHighlight : null)]} //replace with your condition
/>
And add style stylesheet:
var styles = StyleSheet.create({
input: {
//other styles
color:'#fff'
},
inputHighlight: {
color:'#ddd'
}
});
Upvotes: 2