0

Good Morning , I tried a simple component with react-native that changes the color of my button while onFocus().I can't find how to change the color . Here is my component . Have you any ideas ?

       import React, {Component} from 'react';

       import {
       StyleSheet,Text, View, Button,
      } from 'react-native';

     export default class App extends Component {
     render() {
     return (

    <View style={styles.inputContainer}>

      <TextInput

        maxHeight={200}


        style={styles.textInput}

        ref={(r) => {

          this.textInputRef = r;

        }}

        placeholder={'Message'}

        underlineColorAndroid="transparent"

        onFocus={()=>{/*Here i awant to change the color of Button }}

        testID={'input'}

      />

     <Button color="transparent" id="ScanButton"
        onPress={() => this.setState({text: 'Placeholder Text'})}
        title="Scan Barcode"
      />

    </View>

)}

2 Answers 2

1

First Initialize your variable

constructor(props) {
        super(props);
        this.state = {
            isFocus: false
        }
    }

In your TextInput add two props onFocus() and onBlur()

 <TextInput
        maxHeight={200}
        style={styles.textInput}
        ref={(r) => {
          this.textInputRef = r;
        }}
        placeholder={'Message'}
        underlineColorAndroid="transparent"
        onBlur={() => this.onBlur()}
        onFocus={() => this.onFocus()}
        testID={'input'}
      />

add two methods in your class to change the state

 onFocus() {
        this.setState({
            isFocus: true
        })
    }

 onBlur() {
        this.setState({
            isFocus: false
        })
    }

and your button style will be like that

<Button  
       color={this.state.isFocus ? 'red' : 'green'}
        id="ScanButton"
        onPress={() => this.setState({text: 'Placeholder Text'})}
        title="Scan Barcode"
      />
Sign up to request clarification or add additional context in comments.

Comments

0
 style={{color: this.props.focused ? '#8B327C' :'#3F8B99'}}

try something like this

5 Comments

Hi where should i add this line please ?
add this ass a style to component you want its color changed
it doesn't work because the only way to change the color of a button in react native is to set directly color:' black' without passing by style .
@Roozbeh thank u it works with your solution i just did it like that : <Button color={ this.state.focused ? '#3F8B99' :'transparent'} onPress={() => this.setState({text: 'Placeholder Text'})} title="Scan Barcode" />

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.