In the previous exercise, we used the StyleSheet
API to reuse styling rules and improve the readability of our components.
Besides these benefits, one of the biggest drawbacks is that the styling is mostly static.
There is no good way to change the styling rules within StyleSheet
based on user interaction.
Luckily, the styling property is more advanced than it looks.
The style
property also accepts an array of inline style objects or StyleSheet
references.
It is similar to applying multiple CSS classes to a HTML element, e.g. <div class="box red">
.
Using this array with conditionally added styles, we can make the styling dynamic based on user interaction.
const AwesomeBox = (props) => ( <View style={[styles.box, props.isActive && { backgroundColor: 'purple' }]} /> ); const styles = StyleSheet.create({ box: { width: 100, height: 100, backgroundColor: 'red', }, });
In this example, we are changing the background color to purple when the isActive
property is true.
We can combine both StyleSheet
references and inline styling objects.
The eventual styling is created by applying all styles in the array from left to right.
Instructions
Let’s try to apply these styling arrays to our box example.
Change the background color for the box from red
to blue
, without changing the StyleSheet
.
Use the existing styles.box
and an inline styling object to “overwrite” the background color.
Great! Because we are using JavaScript for our styling, we can tie it to user interaction. Let’s make our boxes interactive by capturing when users press on a box.
Instead of using a button, let’s try a new core component called Pressable
.
It contains the functionality of a button, but it doesn’t include how the button is rendered.
We can define that by rendering any content within the Pressable
component.
Wrap our Box
, in the App
component, in a Pressable
component.
Nice! A cool feature from Pressable
is that it informs the child elements if the Pressable
is currently pressed or not.
With this property, we don’t have to implement a state variable to keep track of this interaction.
This only works when using a method as a child in the Pressable
component. You can add that by using:
<Pressable> {(state) => <Box pressed={state.pressed} />} </Pressable>
Now change the code to make our box blue only when a user presses the box. To make it work in the preview, also add the method listed above.
Awesome! If you press the box, it should change the background color to blue. This is a simple demonstration of using JavaScript, style arrays, and inline style objects to make our components look interactive.
Press Run to continue to the next exercise.