Day 7: Handling Touches, Styles, and Layout
It’s already day 7 of my #ReactNativeIn30Days! In today’s’ post, I will touch on the following:
- Handling Touches
- Touchables
- Styles
- Layout with Flexbox
Handling Touches
In one of my previous posts, I talked about how users interact with an app by typing into text fields. The most common way mobile users interact with an app is through touch.
React Native allows us to use several touch gestures to interact with an app. Some of these gestures are swiping, scrolling, tapping, pinching, etc. But in the example below, I will focus on just the tap gesture.
Code:
Explanation:
Line 14: We pass a function to the prop called onPress. The function is triggered when the button is pressed by displaying an alert box on the screen with a message that the button was clicked
Result:
Touchables
React Native provides us with “Touchable” components that come with no styling out of the box. This can be used in place of the Button. But the disadvantage here is that you’ll need to style it for it to look like a button since it comes with no style. Different feedback is sent based on the Touchable component used. Examples of these Touchable components are:
- TouchableHighlight: this can be used in place of a button or link
- TouchableNativeFeedback: available only on Android.
- TouchableOpacity
- TouchableWithoutFeedback
Style
React Native uses javascript for styling. The names and values match most of the CSS properties and values used in the web. Just that camel case naming style is used instead of using names with a hyphen. For example, background-color will be written as backgroundColor instead.
React Native core components accepts a named prop called style which accepts a key-pair value (object).
Also, react-native provides us with a component called StyleSheet which helps to group our styles in a single object as they grow. Below is an example of how to use the Stylesheet component to organize our styles.
Code:
Explanation:
Line 21: We create a new constant called styles and assign it to Stylesheet.create() which takes in an object.
Layout with Flexbox
First of all, the flexbox is designed to allow much consistent design across various screen sizes. It is much easier to layout elements on your screen using flexbox in react-native. React Native fully supports flexbox and it is important to know how flexbox works to make it easier for you to style your elements.
Wrap up:
We looked at how to handle touches and styles in React Native as well as the important role flexbox play in allowing us to have that flexibility to design our layouts.
In my next post, I will combine all the basics I have learned so far and come up with a small project to validate the skills acquired.
Github Repo: https://github.com/victorbruce/react-native30