React Native: Custom Buttons with Cssta

We’re going to be making this button with React Native and Cssta. Yes, it’s animated!

To make buttons with React Native, it provides TouchableOpacity for iOS and TouchableHighlight on Android. These are great for most cases, but to create our example, we’ll have to go lower level.

React Native provides TouchableWithoutFeedback for this. Below is a utility class that makes it a bit easier to use.

We record whether we’re interacting with it, and render our child component with this information. We use a function for the child component, and the function takes one parameter that indicates whether the Touchable is interactive, and returns another component based on that information.

<TouchableCustom>
{active => (<CustomElement active={active} />)}
</TouchableCustom>

Theming

We’re going to implement CustomElement using Cssta — it’s like styled-components, but provides us with a few features that will make this easier. If you haven’t, hopefully it should be intuitive enough as to what’s going on!

To get a button with text inside, we have to make two components: a themed container (ButtonContainer), and a themed text element (ButtonText).

We’ll then integrate them in the TouchableCustom component.

A change from styled-components: the [active] CSS selector actually queries React properties. For ButtonContainer, the background colour will be applied when the property active is equal to true. I find this to be a lot more readable than having functions in the middle of your stylesheet!

We end up with something that looks like this:

Normal state
Pressed state

This is an okay start, but we have a duplication in the colours. Also, we have to set active on both the container and the text. Cssta supports CSS custom properties in React Native, which we can use here to simplify our code.

We’ll make a primary variable that contains our orange colour, and foreground and background variables that change based on whether the button is active.

When the property active is true, we switch the values of foreground and background. This not only updates ButtonContainer, but also ButtonText, which means we can remove the [active] selector from there!

If we want to get really into it, we can also modify the colours using the CSS color function (see here).

Lastly, we want to add some animations. Cssta also supports CSS transitions: all we need to do is change View and Text to their Animated.<Class> equivalents and add the CSS to transition them.

And that’s it. We have an animated button.

Make sure when if you use this in production, you use babel-plugin-cssta — it’ll pre-parse all the CSS we wrote, so we don’t do that at runtime.

You can see the code for the example here. You can read the Cssta docs here!

We can use our TouchableCustom class to create more of these buttons easily.