How to change only the active button background color [React-Native]

Viewed 564
import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';

class App extends Component {
  constructor(props){
    super(props)
    this.state={
      selected:null
    }
  }

  handle=()=>{
    this.setState({selected:1})
  }

  render() {
    return (
      <View>
        <TouchableOpacity style={[styles.Btn, {backgroundColor:this.state.selected===1?"green":"white"}]} onPress={this.handle}>
          <Text style={styles.BtnText}>Button 1</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.Btn} onPress={this.handle}>
          <Text style={styles.BtnText}>Button 2</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.Btn} onPress={this.handle}>
          <Text style={styles.BtnText}>Button 3</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  Btn: {
    borderWidth: 1,
    width: 100,
    height: 20,
    borderRadius: 8,
    margin: 5,
    padding: 10,

    justifyContent: 'center',
    flexDirection: 'row',
    alignItems: 'center',
  },

  BtnText: {
    fontSize: 15,
  },
});

export default App;

Snack Link : https://snack.expo.dev/U_fX-6Tao-

I want to make it so when I click a button, the active button backgroundColor should change to "green" and text to "white" and the rest of the buttons backgroundColor and textColor should stay "red". But when I click another button then that button should become active and the previous active button should get back to its normal state.

It would be wonderful if you could also explain the logic behind it as I'm a newbie in React Native.

Thank you.

1 Answers

You are always setting the active button to the first one. Also, I would use an array to render the buttons. I would do something like this:

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      selected: null
    }
  }

  handlePress = (item) => {
    this.setState({ selected: item })
  }

  render() {
    return (
      <View>
        {[...Array(3).keys()].map((item) => {
          return (
            <TouchableOpacity key={item} style={[styles.Btn, {backgroundColor: this.state.selected === item ? "green" : "white" }]} onPress={() => this.handlePress(item)}>
              <Text style={styles.BtnText}>Button {item + 1}</Text>
            </TouchableOpacity>
          )
        })}
      </View>
    );
  }
}
Related