🧱Laying the Foundation
How to work with React Native components.
Core Components
You can find the official list of core components that react-native has to offer here. In the example below, we'll be using View
, Button
and TextInput
as an example to get started with the core components of react native. You can find the full list of core react native components here.
Styles
React Native View
component, by default, uses the flexbox
to align it's content. There are two basic ways in which we can style our react native apps:
Inline styles
StyleSheet
objects
Inline Styles
For the above basic example, lets add some basic inline styles.
We can see the result in the simulator:
StyleSheet Object
It is recommended to use StyleSheet objects since they tend to provide performance improvements and are also developer friendly since they throw errors in case we provide any erroneous style properties to our components.
Our app will look the same as it looked with inline styles, only advantage with StyleSheet objects is better performance and better developer experience.
Flexbox Deepdive
Let's dive into the basics of flexbox with react native using simple boxes.
This is how our app looks currently:
Flex Direction
React Native, by default uses Flexbox for every view. It also uses the flex-direction
as column
for every view by default. We can change the direction from column (default), to row.
Then, our coloured squares would be aligned in a row. There are 4 options that we can provide to this flex property:
row
column
row-reverse
column-reverse
Concept of Axis
Every flex container has two axes, viz. the main axis
and the cross-axis
, which depend upon your flex-direction.
If our flex-direction is
row
, the main axis will be from left-to-right, and the cross axis will be from top-to-bottom.If our flex-direction is
row-reverse
, the main axis will be from right-to-left, and the cross axis will be from bottom-to-top.If our flex-direction is
column
, the main axis will be from top-to-bottom, and the cross axis will be from left-to-right.if our flex-direction is
column-reverse
, the main axis will be from bottom-to-top, and the cross axis will be from right-to-left.
The basic flex properties justifyContent
and alignItems
work based on these axes. The justifyContent
property works on the main axis, whereas the alignItems
property works on the cross axis.
This is how our app looks now, with the above flex properties applied to the main View
, which is a flex container.
The flex
property
flex
propertyIf we want to provide a width to the children inside of a flex container, we can do so using the flex
property. This property is applied to items inside of a flexbox, which then controls the space that a child takes within the parent container. We can grow or shrink our flex items with the help of this property.
To read more on FlexBox with React Native, check out the official docs.
Last updated