tab_stopp
tab_stopp

Reputation: 49

Change the backgroundcolor of Touchable / Pressable Item after pressing

I'm currently working on an app prototype with react native. There's a lot out there on how to change the color of a component, here Touchable or Pressable, when pressing it (=> onPress). But how do i change the backgroundcolor of such a component permanently after clicking – with onPressOut?. Example:

simple "Click me" component that has a green background by default. If clicked once, it should change to a red background. Clicked once again, it should go back to green (and so on).

Can you help me with this?

Upvotes: 1

Views: 6595

Answers (2)

Hugobop
Hugobop

Reputation: 470

2023 Way:

import { Pressable, StyleSheet, Text } from 'react-native'

const App = props => {
    return (
        <Pressable
          onPress={() => someFunction()}
          style={({ pressed }) => [
              { backgroundColor: pressed ? 'red' : 'transparent' },
              styles.otherStyles
          ]}
      >
        <Text>Press Me</Text>
      </Pressable>
   )

}

credit: https://medium.com/timeless/a-simple-touch-feedback-with-the-new-pressable-component-b4d91c35456

Upvotes: 5

Deivison Sporteman
Deivison Sporteman

Reputation: 2382

You need to control it using the state of component.

I did a live demo for you:

https://codesandbox.io/s/silent-sea-5331l?file=/src/App.js

import React, { useState } from "react";
import { View, TouchableOpacity } from "react-native";

const App = props => {
  const [selected, setSelected] = useState(false);

  return (
    <View style={{ width: "30%", alignItems: "center", marginTop: 20 }}>
      <TouchableOpacity
        onPress={() => setSelected(!selected)}
        style={{ backgroundColor: selected ? "red" : "transparent" }}
      >
        Press me
      </TouchableOpacity>
    </View>
  );
};

export default App;

Upvotes: 2

Related Questions