3
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.

2 Answers 2

2

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>
    );
  }
}
3
  • Thanks for your response @ataravati. I tried it but it's not working. Could you please take a look at it. Here's the snack link: Code
    – user17473297
    Commented Nov 22, 2021 at 8:04
  • I had forgotten to rename the call to the handlePress function. You should've figured it out on your own. Please use the updated code.
    – ataravati
    Commented Nov 22, 2021 at 15:05
  • 1
    I tried but couldn't find out why your previous wasn't working. Thanks for your help.
    – user17473297
    Commented Nov 22, 2021 at 18:33
0

I created an Themed component(OK I did not create it. It is there when I create the app with Expo).

import { useState } from 'react';
import { TouchableOpacity as DefaultTouchableOpacity } from 'react-native';

export type TouchableProps = DefaultTouchableOpacity['props'] & { activeBgColor?: string };

export function TouchableOpacity(props: TouchableProps) {
  const [active, setActive] = useState(false);
  const { style, activeBgColor, ...otherProps } = props;
  if (activeBgColor) {
    return (
      <DefaultTouchableOpacity
        style={[style, active ? { backgroundColor: activeBgColor } : {}]}
        activeOpacity={0.8}
        onPressIn={() => setActive(true)}
        onPressOut={() => setActive(false)}
        {...otherProps}
      />
    );
  }
  return <DefaultTouchableOpacity style={style} activeOpacity={0.8} {...otherProps} />;
}

Then I use this TouchableOpacity everywhere.

<TouchableOpacity
  style={tw`rounded-sm h-10 px-2 justify-center items-center w-1/5 bg-sky-400`}
  activeBgColor={tw.color('bg-sky-600')}
>
  <Text style={tw`text-white font-bold`}>a Button</Text>
</TouchableOpacity>

Oh I am writing TailwindCSS with twrnc by the way. You will love it.

See the screenshot below.

enter image description here