Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a button to change the color of text

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

like image 515
dkershaw Avatar asked Nov 22 '17 04:11

dkershaw


1 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

like image 74
Vivek Doshi Avatar answered Oct 04 '22 03:10

Vivek Doshi