Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Dynamically Change View’s Background Color

I’m trying to make an app where the background color changes every time you tap the screen. I have the tap event working, but the I don’t know how to change the background color.

Here is my code right now:

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)
    }
    onClick() {
        console.log('clicked ')
    }
    render() {
        return (
            <TouchableHighlight onPress={ this.onClick } style={styles.container}>
                <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);

I’d like to have the background regenerate every time the screen is tapped.

like image 627
Hum4n01d Avatar asked Feb 01 '17 19:02

Hum4n01d


People also ask

How do you change background color of view on press in React Native?

To change background color on click in React: Set the onClick prop on the element. When the element is clicked, set the active state. Use a ternary operator to conditionally set the background color based on the state variable.

How do I change the background in React Native?

In React Native we can use backgroundColor property of stylesheet to change the screen color to white, black, yellow etc. React Native beginners makes mistake by using background property instead of backgroundColor . This works in React and HTML but not in React native. The hex code for white color is #FFFFFF or #FFF.


Video Answer


3 Answers

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);
like image 161
David Avatar answered Nov 15 '22 22:11

David


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);
like image 33
Yasemin çidem Avatar answered Nov 15 '22 20:11

Yasemin çidem


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]}
like image 20
Im Batman Avatar answered Nov 15 '22 21:11

Im Batman