DEV Community

Cover image for React Native Conditional Button styling for iOS.
Barkley Santo
Barkley Santo

Posted on

2 2

React Native Conditional Button styling for iOS.

React Native (RN) allows us to write code in one language for mobile apps instead of resorting to writing platform specific code.

However there are some things in RN that do require platform specific code.

Below we have a custom button component, the effect we're looking at now is the button changing color when pressed 👆🏾.

RN gives us a special property we can use for this effect, it's called android_ripple. Once the button is pressed, the ripple property applies the color we provided to the button.

Check it out!

    <View style={styles.buttonOuterContainer}>
      <Pressable
        onPress={pressHandler}
        android_ripple={{ color: "#540233" }}
      >
        <Text style={styles.buttonText}>{children}</Text>
      </Pressable>
    </View>

Enter fullscreen mode Exit fullscreen mode

android touch gif

But since this is an Android property 👽, it won't work on iOS devices, so we need to finesse some JS for this.

The style attribute in a component can either take a style object directly or an arrow function, so we can run some JS directly inside of it.

   <View style={styles.buttonOuterContainer}>
      <Pressable
        onPress={pressHandler}
        android_ripple={{ color: "#540233" }} //Android color change


        style={({ pressed }) => // iOS color change
          pressed
            ? [styles.buttonInnerContainer, styles.pressed]
            : styles.buttonInnerContainer
        }
      >
        <Text style={styles.buttonText}>{children}</Text>
      </Pressable>
    </View>
Enter fullscreen mode Exit fullscreen mode

Here's what we get.
ios touch gif

The Pressable component automatically passes a pressed value (which is a boolean) to the function, and then we can use that boolean in a ternary operator.

We’re allowed to return/add multiple styles objects in an array from this ternary operator, so we’re not limited to one ‘key’ from the stylesheet in this case. We're applying both the base button style and the button press color change here.

It ends up reading as “if pressed is true, apply both style objects from this array, if not, just apply a single style”.

A quick one, but good to know, cheers 🥂

A puppy for your troubles (source):
a pupper

Cover image by Katya Ross

Top comments (0)

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay