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'.
3 Answers
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'
}
});
9 Comments
this.state.checkSwitch has your expected value? To check, add { console.log(this.state.checkSwitch) } somewhere in your render()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',
},
});
4 Comments
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>
);
}
<TextInput style={{color: this.state.color}}/>