React Native Dynamically Change View’s Background Color
You can change the background color by using this.setState
Set the initial background color in your constructor
this.state = {
backgroundColor: randomHex()
}
in your render
function change your style prop to:
[styles.container, {backgroundColor: this.state.backgroundColor}]
and onClick
add
this.setState({backgroundColor: randomHex()});
Heres the full code
import React, { Component } from "react";
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
} from "react-native";
let randomHex = () => {
let letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
export default class randomBackground extends Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.state = {
backgroundColor: randomHex(),
};
}
onClick() {
console.log("clicked ");
this.setState({ backgroundColor: randomHex() });
}
render() {
return (
<TouchableHighlight
onPress={this.onClick}
style={[
styles.container,
{ backgroundColor: this.state.backgroundColor },
]}
>
<View>
<Text style={styles.instructions}>Tap to change the background</Text>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: randomHex(),
},
instructions: {
color: "white",
},
});
AppRegistry.registerComponent("randomBackground", () => randomBackground);
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight
} from 'react-native';
export default class randomBackground extends Component {
state={
currentColor:"#FFFFF"
}
onClick() {
let letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
this.setState({currentColor:color})
}
render() {
return (
<TouchableHighlight onPress={ this.onClick.bind(this) } {[styles.container, {backgroundColor: this.state.currentColor}]}>
<View>
<Text style={styles.instructions}>
Tap to change the background
</Text>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
instructions: {
color: "white"
}
});
AppRegistry.registerComponent('randomBackground', () => randomBackground);
When you simply want to change series of button style change. (example Tab bar buttons, one button selected others not ) simply use conditional styles
style={[this.state.yourstate ? styles.selectedButtonStyle : styles.normalButtonStyle]}