Learn

One of the most fundamental core components is the View component. With View, you can create responsive layouts using flexbox or add basic styling to nested components.

The component is best comparable with a div HTML element. Just like div, the View component is not visible unless styling is applied. We can apply this styling through the style property.

<View style={{ width: 250, backgroundColor: 'yellow' }}> ... </View>

Expo and React Native don’t use CSS. This method of styling is not available on native platforms. Instead of using CSS, we can write our styling using plain JavaScript objects. These objects use the same CSS properties but they are written in “camelCase”. All styling properties are explained in the style documentation.

Instructions

1.

Let’s start by rendering a View without any styling.

2.

Great, we just rendered our View component. Remember that without any styling, the View component isn’t visible.

Let’s modify the code to display our View as a red box. For that, we need to apply a fixed width, height, and background color. Set the width and height to 100 and the background color to red.

3.

There it is! By telling the View component how to behave, we can add basic visible characteristics using the style property.

This red box is stuck in the upper left corner of our app. We can fix that by using flexbox.

Expo and React Native supports a slightly different form of flexbox compared to web. Instead of writing display: flex, all components are a flexbox by default. We can enable the flexbox behavior by using the flex property in our style object. All supported flexbox properties are explained in the flexbox documentation.

<View style={{ flex: 1 }}> ... </View>

Let’s add an invisible View component that positions our red box right in the middle of our screen, using the flex, justifyContent, and alignItems properties.

4.

Awesome, right? Not all View components have to be visible – in this example we told the parent View to behave like a flexbox container. By adding the alignItems: 'center' and justifyContent: 'center' rules, this flexbox container positions the red box right in the middle of our screen.

Using flexbox is important to create responsive styling in React Native. Building apps for both Android and iOS also implies building for multiple screen sizes. In the next lesson, you’ll learn more about styling and creating complex flexbox layouts.

Let’s experiment with our flexbox a bit more. What happens when another View is added to the flexbox?

Add another box with similar styling properties as our red box. To make it more distinct, change the backgroundColor to something else, like blue.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?