Using a button to change the color of text

Viewed 5744

I'm trying to create a simple React Native app that:

  1. Renders "Hello, [name]!" when a user enters a name (this part works)
  2. Changes the "Hello, [name]!" text color when a button is pressed.

Any ideas as to how I should go about this?

I gave this an initial state of black, but that doesn't even seem to be doing anything.

What I want to happen is to trigger makeRed when the red button is clicked, which will turn the text red. Once I have this working, I'll add more color buttons.

Thank you!

See below for my App.js code. All other files were left in their default state.

import React, { Component } from 'react';
import {
  AppRegistry,
  Platform,
  StyleSheet,
  Text,
  TextInput,
  View,
  Button
} from 'react-native';

export default class App extends Component<{}> {
  constructor(props) {
    super(props);
    this.state = {
      text: 'World',
      color: 'black'
    };
  }

  makeRed = () => {
    this.setState({
      color: 'red'
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={[styles.welcome, {color: undefined}]}>
          Hello, {this.state.text}!
        </Text>
        <TextInput
          style={styles.instructions}
          placeholder="Enter a name here!"
          onChangeText={(text) => this.setState({text})}
        />
        <Button
          title='⬤'
          onPress={this.makeRed}
          color='red'
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 40,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Here's a screenshot of the app for reference: app screenshot

2 Answers

All you need to do is change this :

style={[styles.welcome, {color: undefined}]}

To

style={[styles.welcome, {color : this.state.color }]}

Please check : WORKING DEMO

color is not referenced as a property of state , in the style of the Text component. Try this as the Text element:

<Text style={{color: this.state.color, ...styles.welcome}}>
  Hello, {this.state.text}!
</Text>

And, makeRed needs to be have it's context bound in the constructor, or else this.setState will be undefined. Like this (under super(props)):

this.makeRed = this.makeRed.bind(this)
Related