0% found this document useful (0 votes)
30 views107 pages

Benefits of React Native

Why you must use React Native as mobile developer...

Uploaded by

muchape
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views107 pages

Benefits of React Native

Why you must use React Native as mobile developer...

Uploaded by

muchape
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 107

Benefits of React Native

Now that you know what React Native is, let’s explore it further and focus on the benefits that using
React Native can bring. This way, you will be confident about the tool you will use to build the Little
Lemon app.

In this reading, you will learn about the benefits of React Native and how to explain why it is a
practical choice for building cross-platform mobile apps. This will help you decide if React Native is a
good fit for your project.

1. Uses JavaScript
The first benefit of React Native is that it is entirely coded in JavaScript. This means you can use
your existing JavaScript skills and put them to use when building React Native apps.

JavaScript has been the most popular programming language in the world for many years, and its
compatibility with React Native is a huge perk for helping JavaScript developers become mobile
developers.

2. Uses React
The next benefit of using React Native is, as you probably guessed, that it uses React.

To simplify this for you:

JavaScript + React = React Native

JavaScript and React make React Native.

React Native apps are written entirely in JavaScript using React. React is the most popular and in-
demand web framework today and is used by several major companies and startups to build their
web applications. With React Native, you can use React to build mobile applications.

You can also use all the principles learned in React with React Native. This means you can use the
component-based architecture that comes with React. Code sharing between mobile and web
platforms becomes more manageable, saving development costs.

3. Builds Cross-Platform Native Apps


The third benefit of using React Native is that it builds cross-platform apps on both iOS and Android.
But did you know that you can’t distinguish them from an app built using native languages such as
Swift or Kotlin?

With React Native, you build a real native mobile app. It is impressive since you are coding in
JavaScript and rendering components native to the platform. This is one of the reasons why apps
built using React Native have a superior user experience (UX).
React Native provides platform-agnostic components that map directly to the platform’s native user
interface (UI) building blocks. This results in high-quality native apps that offer a great user
experience.

4. Cost Effective
At this point, it may be no surprise to learn that React Native could save you money!

This is because React Native is a cost-effective option for teams. Teams can be smaller in size, with
developers working cross-platform on the same code base. There is no need to support separate
codebases for iOS and Android.

This results in faster development time. This also means that the code is easier to test and debug.
Once you find a bug, it is simultaneously removed in iOS and Android. This eliminates the need to
maintain multiple codebases.

All of these result in an overall reduction in costs!

5. Developer Experience
The last benefit is that, unlike developing traditional native mobile apps, developing React Native
apps is a far superior developer experience. You will enjoy the ease of development, all the
developer tools it comes with, and how straightforward it is to debug.

Let’s explore some features you can utilize to enjoy a great developer experience.

Fast Refresh
React Native supports fast refresh, which gives almost instant feedback for your changes in React
Components while the app is running on an emulator. The quick refresh feature is a big time-saver
for developers. You can see your changes on the emulator as soon as you hit save!

Easy Debugging
Debugging React Native apps is simple since you are essentially debugging JavaScript code. You
can use the Chrome developer tools to debug the JavaScript code. In addition, you can use the
React Developer tools to debug the React Component hierarchy.

Over-the-Air Updates
The next feature, which is another big time-saver, is over-the-air updates. In traditional native apps,
both iOS and Android, the release process can be tedious and getting approval from the app store
can take several days. With React Native, you may be able to avoid this wait, depending on your
changes. App Center’s Code Push is a cloud service that enables React Native developers to deploy
mobile app updates directly to the users’ devices. It acts as a central repository to which developers
can publish updates, and those apps can query for updates. This means small features or bug fixes
can be made available to users immediately, without redistribution through the respective app
stores. Features like Over the Air (OTA) updates make the React Native developer experience
seamless.
Conclusion
The React Native community is growing incredibly fast, and now is a great time to learn.

You should now be more familiar with the benefits of using React Native and understand why it is a
fantastic tool for building cross-platform apps. Hopefully you’ll find it useful for your next project!

Solution: Your first React Native


component
Overview
In the preceding exercise, you created a reusable React component for the Little Lemon mobile app.
Here is the solution code for the exercise to assist you on your learning journey.

Procedure
Step 1: Create Footer Component

Create a LittleLemonFooter component in a new file within the components folder.

This component will print the text needed for the footer.

components/LittleLemonFooter.js

import * as React from 'react';


import { View, Text } from 'react-native';

export default function LittleLemonFooter() {


return (
<View>
<Text>
All rights reserved by Little Lemon, 2022{' '}
</Text>
</View>
);
}
Step 2: Style Footer Component

Below you'll find the code used to style the footer component.

import * as React from 'react';


import { View, Text } from 'react-native';

export default function LittleLemonFooter() {


return (
<View
style={{
backgroundColor: '#F4CE14',
marginBottom: 10,
}}>
<Text
style={{
fontSize: 18,
color: 'black',
textAlign: 'center',
}}>
All rights reserved by Little Lemon, 2022{' '}
</Text>
</View>
);
}
Step 3: Call Footer Component from App Component

Finally, you’ll need to call the footer component from the App component by applying the
following code:

import * as React from 'react';


import { View } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import LittleLemonFooter from './components/LittleLemonFooter';

export default function App() {


return (
<>
<View
style={{
flex: 1,
backgroundColor: '#495E57',
}}>
<LittleLemonHeader />
</View>
<View style={{ backgroundColor: '#495E57' }}>
<LittleLemonFooter />
</View>
</>
);
}

The code block below outlines the outcome of the exercise in its entirety.
components/LittleLemonFooter.js

import * as React from 'react';


import { View, Text } from 'react-native';

export default function LittleLemonFooter() {


return (
<View
style={{
backgroundColor: '#F4CE14',
marginBottom: 10,
}}>
<Text
style={{
fontSize: 18,
color: 'black',
textAlign: 'center',
}}>
All rights reserved by Little Lemon, 2022{' '}
</Text>
</View>
);
}
App.js

import * as React from 'react';


import { View } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import LittleLemonFooter from './components/LittleLemonFooter';
export default function App() {
return (
<>
<View
style={{
flex: 1,
backgroundColor: '#495E57',
}}>
<LittleLemonHeader />
</View>
<View style={{ backgroundColor: '#495E57' }}>
<LittleLemonFooter />
</View>
</>
);
}
The code above produces the following output on the emulator:
Explore the View and Text Components
In an earlier video, you learned how to use the View and Text components which are the
essential core components of React Native.

This reading will explore the code you can write to build the LittleLemonHeader component
using the View and Text component.

Build a Header with the View and Text Components


First, you will build the reusable header component. Keep in mind that you can call this custom
component anything you want, but in this example it will be named LittleLemonHeader.
This component uses both the View and the Text components.

LittleLemonHeader.js

import * as React from 'react';


import { View, Text } from 'react-native';

export default function LittleLemonHeader() {


return (
<View style={{ flex: 0.2, backgroundColor: '#F4CE14' }}>
<Text
style={{ padding: 40, fontSize: 30, color: 'black' }}
numberOfLines={3}>
Welcome
<Text style={{ fontWeight: 'bold' }}> Little Lemon</Text> {' '}
</Text>
</View>
);
}

The component renders a parent View, which has been given a background color and a flex
property of 0.2. This means that the header component will occupy 20 percent of the total space
on the screen.

Next, you will see a Text component that renders the text Welcome. Here the Text
component has been given various styling items — padding of 40 pixels, a font size of 30 and a
text color of black. You will also notice another Text component nested within the parent Text
component. The component renders the text Little Lemon in bold.

The nested Text component inherits all the properties and styling from the parent Text
component. Notice that the number of visible lines have been set to 3 for the parent Text
component.
And that’s it! The Little Lemon header component is complete.

Importing and Rendering the Header


Next, you will import the LittleLemonHeader component that's in the App.js file, which is
the root file of this application. Once it is imported, you can render it within the parent View
component, as shown in the solution code.

Here the parent view has a flex property of 1 and a background color.

App.js

import * as Reactfrom'react';
import{ View } from'react-native';

import LittleLemonHeader from'./components/LittleLemonHeader';

export default function App() {


return (
<View
style={{
flex: 1,
backgroundColor: '#495E57',
}}>
<LittleLemonHeader />
</View>
);
}
In this reading you learned how to use the View and Text components to build custom components
in React Native. Specifically, you utilized these components to make a custom header for the Little
Lemon app.
Exercise: Build a React Native screen

Overview
Previously, you were introduced to two core components: View and Text. If you recall, View
is the basic building block of the user interface that houses other elements, while Text is used to
display text on the screen.

In this activity, you will use these components to create a Welcome screen for the Little Lemon
app. In the process you’ll learn best practices for efficiently building React Native screens in a
mobile app.

Scenario
The Little Lemon app already has a header and footer component, and now you have been asked
to create a Welcome screen for the app. This screen will contain a welcome message as
demonstrated below:
Starter Code
Use the code below and build upon it to complete this exercise. The code can be downloaded
from the zipped folder below:

Instructions
Step 1: Create a Welcome Screen

Your first step is to create a Welcome screen. Create a file named WelcomeScreen.js within
your source project folder. This will contain the code to display the welcome text.

The screen should display the following title:

Welcome to Little Lemon

Below this title you should have the following subheading:

Little Lemon is a charming neighborhood bistro that serves simple food and classic
cocktails in a lively but casual environment. We would love to hear more about your
experience with us!

Hint: Think about how to structure this with components. Where should the Text component be
relative to View?

Step 2: Style Welcome Screen

The next step is to add styles to your Welcome screen. Don't forget that this is a creative
process, so feel free to choose any styles, font sizes and colors that you think suit the screenshot
given in the scenario.

Hint: You can follow the same styling patterns and colors used so far in the starter code.

Step 3: Render the Welcome Screen from the App Component

In this step, you will call the Welcome screen that you created from the App component. This
ensures that the Welcome screen is rendered on the app.

Hint: Have you imported all the necessary components for rendering?

Conclusion
By completing this exercise, you will demonstrate your understanding and ability to create
screens within your React Native app. You will demonstrate how to use some of the core
components in React Native, such as View and Text while building the Welcome screen for
Little Lemon.

Solution: Build a React Native screen


Overview
In this reading, you will review the solution code for the exercise.

The code block below outlines the outcome of the exercise in its entirety.

WelcomeScreen.js

import * as React from 'react';


import { View, Text } from 'react-native';

export default function WelcomeScreen() {


return (
<View style={{ flex: 1 }}>
<Text
style={{
padding: 40,
fontSize: 30,
color: '#EDEFEE',
textAlign: 'center',
}}>
Welcome to Little Lemon
</Text>
<Text
style={{
fontSize: 24,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
}}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear your experience with us!
</Text>
</View>
);
}
App.js

import * as React from 'react';


import { View, Text } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import LittleLemonFooter from './components/LittleLemonFooter';
import WelcomeScreen from "./WelcomeScreen";

export default function App() {


return (
<>
<View
style={{
flex: 1,
backgroundColor: '#495E57',
}}>
<LittleLemonHeader />
<WelcomeScreen />
</View>
<View style={{ backgroundColor: '#495E57' }}>
<LittleLemonFooter />
</View>
</>
);
}

The code above produces the following output on the emulator:


Procedure
Next, examine a breakdown of the individual steps.

Step 1: Create a Welcome Screen

First, you’ll need to create a WelcomeScreen.js file within the source folder of your project
file.

import * as React from 'react';


import { View, Text } from 'react-native';

export default function WelcomeScreen() {


return (
<View>
<Text>
Welcome to Little Lemon
</Text>
<Text>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear more about your experience with us!
</Text>
</View>
);

Step 2: Style Welcome Screen

The next step is to style the Welcome Screen appropriately. Notice that there are different
styles applied for the title and the subheading.

import * as React from 'react';


import { View, Text } from 'react-native';

export default function WelcomeScreen() {


return (
<View style={{ flex: 1 }}>
<Text
style={{
padding: 40,
fontSize: 30,
color: '#EDEFEE',
textAlign: 'center',
}}>
Welcome to Little Lemon
</Text>
<Text
style={{
fontSize: 24,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
}}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear more about your experience with us!
</Text>
</View>
);
}
Step 3: Render the Welcome Screen from the App Component

Finally, you can call the WelcomeScreen component from the App component with the
following code:

import * as React from 'react';


import { View, Text } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import LittleLemonFooter from './components/LittleLemonFooter';
import WelcomeScreen from "./WelcomeScreen";

export default function App() {


return (
<>
<View
style={{
flex: 1,
backgroundColor: '#495E57',
}}>
<LittleLemonHeader />
<WelcomeScreen />
</View>
<View style={{ backgroundColor: '#495E57' }}>
<LittleLemonFooter />
</View>
</>
);
}

And with that, the screen you created in the WelcomeScreen component should be rendered
through the App component!
Question 3
Which one of the following code snippets correctly represents the Little Lemon app’s Welcome
screen, as created in the previous exercise?

export default function WelcomeScreen() {


return (
<View style={{ flex: 1 }}>
<Text
style={{
padding: 40,
fontSize: 30,
color: '#EDEFEE',
textAlign: 'center',
}}>
Welcome to Little Lemon
</Text>
<Text
style={{
fontSize: 24,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
}}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love

to hear your experience with us!


</Text>
</View>
);
}
Which of the following are true statements about the ScrollView component? Check all that
apply.

Well done! ScrollView must be bounded by a height, because it contains unbounded height
children into a bounded container.

Correct
Well done! ScrollView comes as part of the React Native package, and it must be bounded in
height in order to work.

You would like to create a list for your app that is scrolled horizontally. Which ScrollView prop
would you pass to accomplish this?

Well done! When the horizontal prop is set to ‘true’, the list items are set horizontally.

Explore the ScrollView Component

Previously, you were introduced to the ScrollView component, a core component of React
Native. Now, let’s say you want to display a scrollable list of menu items for the Little Lemon
restaurant.

In this reading, you’ll learn how to do this by exploring the code needed to build the Little
Lemon scrollable menu items.

Create a List
The first step is to create a MenuItems.js file within the components folder of your project.
You can name this component whatever you wish. This component is going to display the
scrollable list of menu items.

Second, you will declare an array of menu items for Little Lemon. This array will be used later to
render the menu items. Observe the code below for the MenuItems component, which contains
the array.
MenuItems.js

import React from 'react';


import { View, Text, ScrollView } from 'react-native';

const menuItemsToDisplay = [
'Hummus \n Moutabal \n Falafel \n Marinated Olives \n Kofta \n Eggplant Salad \
n Lentil Burger \n Smoked Salmon \n Kofta Burger \n Turkish Kebab \n Fries \n But
tered Rice \n Bread Sticks \n Pita Pocket \n Lentil Soup \n Greek Salad \n Rice P
ilaf \n Baklava \n Tartufo \n Tiramisu \n Panna Cotta',
];

const MenuItems = () => {


return (
<View style={{ flex: 0.75 }}>
<ScrollView
style={{
paddingHorizontal: 40,
paddingVertical: 40,
backgroundColor: "black",
}}>
<Text style={{ color: 'white', fontSize: 40, flexWrap: 'wrap' }}>
View Menu
</Text>
<Text style={{ color: '#F4CE14', fontSize: 36 }}>
{menuItemsToDisplay[0]}
</Text>
</ScrollView>
</View>
);
};

export default MenuItems;


Build a ScrollView Component
Within the MenuItems component, you will render the ScrollView component within the
parent view. Keep in mind that the ScrollView should always be bounded by height. You can
see that the ScrollView has been provided with both horizontal and vertical padding of 40
pixels along with a background color.

In addition, the ScrollView has been provided with the prop indicatorStyle with a value
of white. This means that the scroll bar indicator will be white in color. This can be swapped to
black if the background color is light.

And that’s it! The ScrollView is now set up, and will render the menu items from the array.

Import and Render your List


Next, you will need to import the MenuItems component from the App.js file. Once
imported, you will then render the component, as shown in the code.

App.js

import * as React from 'react';


import { View } from 'react-native';
import LittleLemonHeader from './components/LittleLemonHeader';
import MenuItems from './components/MenuItems';

export default function App() {


return (
<View
style={{
flex: 1,
backgroundColor: '#495E57',
}}>
<LittleLemonHeader />
<MenuItems />
</View>
);
}

You should now have a deeper understanding of how to use the ScrollView component to build a
scrollable list of items within your app.
Exercise: Build a scrollable component
Overview
Recently, you learned how to use the ScrollView component in React Native. By now, you
should know that ScrollView can be used to create a scrollable view for lists that are too long
to be contained in one screen.

In this activity, you will use a ScrollView component to create a scrollable Welcome screen
for the Little Lemon app. The skills you will practice here can be applied to building other
scrollable views for your React Native apps.

Scenario
The Little Lemon app has a Welcome screen that is demonstrated in the image below.
Currently, this screen is not scrollable. Because of the large font size used for the text, the
contents do not fit within the confines of one screen, and users cannot view the content in full.

In order to make the content accessible, you have been asked to enhance the Welcome screen
from the previous exercise to make it scrollable. You should also make sure that the scroll
indicator is white, so it matches the Welcome screen styles.

Starter Code
In the first screenshot, the emulator is without a scroll bar. It is then followed by an example of
the emulator where the scrollbar is visible after you have run the code and followed the
instructions.

The starter code can be downloaded as a zipped file here:


Instructions
Step 1: Enhance the Welcome screen to be Scrollable
In this step, you will use the existing code for the Welcome screen and enhance it to be a
scrollable screen instead. Here you can use the ScrollView component, instead of the View
component.

Step 2: Ensure that the scroll indicator is white in color

Next, you will include a prop to the ScrollView component to ensure that the scroll indicator
is white in color.

Conclusion
By completing this exercise, you will demonstrate your understanding and ability to create
scrollable views. You will demonstrate how to use the ScrollView component from React
Native while building the Welcome screen for Little Lemon.

Solution: Build a scrollable component


Overview
In this reading, you will review the solution code for the exercise.

The code block below outlines the outcome of the exercise in its entirety.

WelcomeScreen.js
import * as React from 'react';
import { ScrollView, Text } from 'react-native';

export default function WelcomeScreen() {


return (
<ScrollView indicatorStyle={"white"} style={{ flex: 1 }}>
<Text
style={{
padding: 40,
fontSize: 50,
color: '#EDEFEE',
textAlign: 'center',
}}>
Welcome to Little Lemon
</Text>
<Text
style={{
fontSize: 38,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
}}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear more about your experience with us!
</Text>
</ScrollView>
);
}
App.js

import * as React from 'react';


import { View, Text } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import LittleLemonFooter from './components/LittleLemonFooter';
import WelcomeScreen from "./WelcomeScreen";

export default function App() {


return (
<>
<View
style={{
flex: 1,
backgroundColor: '#495E57',
}}>
<LittleLemonHeader />
<WelcomeScreen />
</View>
<View style={{ backgroundColor: '#495E57' }}>
<LittleLemonFooter />
</View>
</>
);
}

The font size on the Welcome screen is fairly large and needs to be scrollable. The code above
produces the following output on the emulator with a scrollable screen:
Procedure
Next, review the breakdown of the individual steps below.

Step 1: Enhance Welcome Screen to be Scrollable

Modify the Welcome Screen to use ScrollView component instead of the View component
for the parent view.

export default function WelcomeScreen() {


return (
<ScrollView style={{ flex: 1 }}>
<Text
style={{
padding: 40,
fontSize: 50,
color: '#EDEFEE',
textAlign: 'center',
}}>
Welcome to Little Lemon
</Text>
<Text
style={{
fontSize: 38,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
}}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear more about your experience with us!
</Text>
</ScrollView>
);
}
Step 2: Ensure that the scroll indicator is white in color

Pass the prop indicatorStyle to the ScrollView component and give it the value white.
This will ensure that the scroll indicator is white in color.

<ScrollView indicatorStyle={"white"} style={{ flex: 1 }}>

...
Styling using StyleSheet
Previously, you found that you can use the StyleSheet API to abstract away styles. By
moving styles away from the component’s render, you are making the code easier to understand.

In this reading, you’ll learn about the code used to create detailed StyleSheets for the Little
Lemon app. You can then use this to quickly extract styles for the different app elements, such as
containers and headers.

You can create stylesheets specific to each component and keep the stylesheets within the same
file as the component. This will keep the styles closer to the component and makes it easier to
reference.

To create a stylesheet, you will use the create method. The styles can be stored within a
const, as shown below:

const styles = StyleSheet.create({


container: {
flex: 1,
backgroundColor: '#495E57',
},
});

All the styles are abstracted away using the StyleSheet API across all the components you have
created so far.
App.js

import * as React from 'react';


import { View, StyleSheet } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import MenuItems from './components/MenuItems';

export default function App() {


return (
<View style={styles.container}>
<LittleLemonHeader />
<MenuItems />
</View>
);
}

const styles = StyleSheet.create({


container: {
flex: 1,
backgroundColor: '#495E57',
},
});
MenuItems.js

import React from 'react';


import { View, Text, ScrollView, StyleSheet } from 'react-native';

const menuItemsToDisplay = [
'Hummus \nMoutabal \nFalafel \nMarinated Olives \nKofta \nEggplant Salad \nLent
il Burger \nSmoked Salmon \nKofta Burger \nTurkish Kebab \nFries \nButtered Rice
\nBread Sticks \nPita Pocket \nLentil Soup \nGreek Salad \nRice Pilaf \nBaklava \
nTartufo \nTiramisu \nPanna Cotta',
];

const MenuItems = () => {


return (
<View style={menuStyles.container}>
<ScrollView
horizontal={false}
indicatorStyle={'white'}
style={menuStyles.innerContainer}>
<Text style={menuStyles.headerText}>View Menu</Text>
<Text style={menuStyles.itemText}>{menuItemsToDisplay[0]}</Text>
</ScrollView>
</View>
);
};

const menuStyles = StyleSheet.create({


container: {
flex: 0.75,
},
innerContainer: {
paddingHorizontal: 40,
paddingVertical: 40,
backgroundColor: 'black',
},
headerText: {
color: 'white',
fontSize: 40,
flexWrap: 'wrap',
},
itemText: {
color: '#F4CE14',
fontSize: 36,
},
});
export default MenuItems;
LittleLemonHeader.js

import * as React from 'react';


import { View, Text, StyleSheet } from 'react-native';

export default function LittleLemonHeader() {


return (
<View style={headerStyles.container}>
<Text style={headerStyles.headerText}>
Welcome to
<Text style={headerStyles.innerText}> Little Lemon</Text>
</Text>
</View>
);
}

const headerStyles = StyleSheet.create({


container: {
backgroundColor: '#F4CE14',
},
headerText: {
padding: 40,
fontSize: 30,
color: 'black',
textAlign: 'center',
},
innerText: {
fontWeight: 'bold',
},
});
By following this approach, you should now have a better idea of how to use the StyleSheet API to
store your styles in an organized way and to reference them as needed to apply to your components.

Exercise: Style a component


Overview
So far you have learned some of the core React Native components and have learned how to style
them effectively. You’ve also discovered that inline styling, which is the practice of keeping styles
within a component’s render, can become unmanageable with larger apps. Fortunately, you have
the StyleSheet API at your disposal for keeping styles neatly in one place.

In this exercise, you will style a component and add the styles to the StyleSheet API.

Scenario
The Little Lemon app currently has some styling applied to the components. However, you have
been asked to update the styling to achieve a different appearance. You should utilize the
StyleSheet API to abstract the styles from the component’s render. Make sure that the component
code is readable and clean.

Here is how the app currently appears:


You will need to modify the app to match the styling shown below:
The colors displayed in the image above can be applied with the following values:

#EE9972, #333333, #EDEFEE, black and white.

Starter Code
You can download the starter code for this exercise from the zipped folder below:

Instructions
Step 1: Update Styles of Components to match Scenario

Your first step in this exercise is to update the styles of the given code to match the screenshot
given in the scenario. Make sure to use the appropriate colors, padding and overall styling theme
shown in the scenario.

Step 2: Extract All Styles to StyleSheet API

In this step, you will extract all the styles per component into its own StyleSheet API. This
will ensure that your component code is readable. A best practice is to provide meaningful names
to all your styles so that you can easily identify the style or where it is used.

Conclusion
By completing this exercise, you will demonstrate your understanding and ability to style React
Native components. You will have demonstrated how to use the StyleSheet API to abstract
away styles while keeping the component code clean and readable.

Mark as completed
Like
Dislike
Report an issue

Solution: Style a component


Overview
In this reading, you will review the solution code for the exercise.

The image below demonstrates the expected output of the exercise. Follow each step below to
explore the solution code.
Procedure
Here is a breakdown of the individual steps.

Step 1: Update Styles of Components to match Scenario

In this step, you will update the styles in each component to match the screenshots provided. The
components now have different background colors, font style and text color. Update the
necessary styles to match the recommended output.

LittleLemonFooter.js

import * as React from 'react';


import { View, Text } from 'react-native';

export default function LittleLemonFooter() {


return (
<View
style={{
backgroundColor: '#EE9972',
marginBottom: 20,
}}>
<Text
style={{
fontSize: 18,
color: 'black',
textAlign: 'center',
fontStyle: 'italic',
}}>
All rights reserved by Little Lemon, 2022{' '}
</Text>
</View>
);
}
LittleLemonHeader.js

import * as React from 'react';


import { View, Text } from 'react-native';

export default function LittleLemonHeader() {


return (
<View style={{ backgroundColor: '#EE9972' }}>
<Text style={{ padding: 40, fontSize: 30, color: 'black', textAlign: "cent
er" }}>
Little Lemon
</Text>
</View>
);
}
WelcomeScreen.js

import * as React from 'react';


import { ScrollView, Text } from 'react-native';

export default function WelcomeScreen() {


return (
<ScrollView indicatorStyle="white" style={{ flex: 1 }}>
<Text
style={{
padding: 40,
fontSize: 30,
color: '#EDEFEE',
textAlign: 'center',
}}>
Welcome to Little Lemon
</Text>
<Text
style={{
fontSize: 24,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
}}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear more about your experience with us!
</Text>
</ScrollView>
);
}
App.js

import * as React from 'react';


import { View, Text } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import LittleLemonFooter from './components/LittleLemonFooter';
import WelcomeScreen from "./WelcomeScreen";

export default function App() {


return (
<>
<View
style={{
flex: 1,
backgroundColor: '#333333',
}}>
<LittleLemonHeader />
<WelcomeScreen />
</View>
<View style={{ backgroundColor: '#333333' }}>
<LittleLemonFooter />
</View>
</>
);
}
Step 2: Extract All Styles to StyleSheet API

In this step, ensure to extract the styles away from the component’s render and instead add them
to the StyleSheet const. This way the styles are given meaningful names and do not mix with
the JSX code within the component.

Refactor WelcomeScreen.js

import * as React from 'react';


import { ScrollView, Text, StyleSheet } from 'react-native';

export default function WelcomeScreen() {


return (
<ScrollView indicatorStyle="white" style={styles.container}>
<Text style={styles.headerText}>Welcome to Little Lemon</Text>
<Text style={styles.regularText}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear more about your experience with us!
</Text>
</ScrollView>
);
}

const styles = StyleSheet.create({


container: {
flex: 1,
},
headerText: {
padding: 40,
fontSize: 30,
color: '#EDEFEE',
textAlign: 'center',
},
regularText: {
fontSize: 24,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
},
});
Refactor LittleLemonHeader.js

import * as React from 'react';


import { View, Text, StyleSheet } from 'react-native';

export default function LittleLemonHeader() {


return (
<View style={styles.container}>
<Text style={styles.headerText}>Little Lemon</Text>
</View>
);
}

const styles = StyleSheet.create({


container: {
backgroundColor: '#EE9972',
},
headerText: {
padding: 40,
fontSize: 30,
color: 'black',
textAlign: 'center',
},
});
Refactor LittleLemonFooter.js

import * as React from 'react';


import { View, Text, StyleSheet } from 'react-native';

export default function LittleLemonFooter() {


return (
<View style={styles.container}>
<Text style={styles.footerText}>
All rights reserved by Little Lemon, 2022{' '}
</Text>
</View>
);
}

const styles = StyleSheet.create({


container: {
backgroundColor: '#EE9972',
marginBottom: 20,
},
footerText: {
fontSize: 18,
color: 'black',
textAlign: 'center',
fontStyle: 'italic',
},
});
Refactor App.js

import * as React from 'react';


import { View, Text, StyleSheet } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import LittleLemonFooter from './components/LittleLemonFooter';
import WelcomeScreen from './WelcomeScreen';

export default function App() {


return (
<>
<View style={styles.container}>
<LittleLemonHeader />
<WelcomeScreen />
</View>
<View style={styles.footerContainer}>
<LittleLemonFooter />
</View>
</>
);
}

const styles = StyleSheet.create({


container: {
flex: 1,
backgroundColor: '#333333',
},
footerContainer: { backgroundColor: '#333333' },
});
Explore the FlatList Component
In an earlier video, you learned how to use the FlatList component to render large lists efficiently.
Now, let’s explore the code from that video in greater detail to build the FlatList component to
display an extensive list of menu items for the Little Lemon app.

Let’s start with a list of menu items you want to display on the Little Lemon menu. It is declared as
an array of objects. Each item contains a name representing the menu item’s name and a unique id.

const menuItemsToDisplay = [
{ name: 'Hummus', id: '1A' },
{ name: 'Moutabal', id: '2B' },
{ name: 'Falafel', id: '3C' },
{ name: 'Marinated Olives', id: '4D' },
{ name: 'Kofta', id: '5E' },
{ name: 'Eggplant Salad', id: '6F' },
{ name: 'Lentil Burger', id: '7G' },
{ name: 'Smoked Salmon', id: '8H' },
{ name: 'Kofta Burger', id: '9I' },
{ name: 'Turkish Kebab', id: '10J' },
{ name: 'Fries', id: '11K' },
{ name: 'Buttered Rice', id: '12L' },
{ name: 'Bread Sticks', id: '13M' },
{ name: 'Pita Pocket', id: '14N' },
{ name: 'Lentil Soup', id: '15O' },
{ name: 'Greek Salad', id: '16Q' },
{ name: 'Rice Pilaf', id: '17R' },
{ name: 'Baklava', id: '18S' },
{ name: 'Tartufo', id: '19T' },
{ name: 'Tartufo', id: '20U' },
{ name: 'Tiramisu', id: '21V' },
{ name: 'Panna Cotta', id: '22W' },
];
To use the FlatList component, you will need to import it directly from the React Native package,
since it is a core component. Use the following code snippet:

import { View, Text, StyleSheet, FlatList } from 'react-native';

The FlatList component has two required props you will need to pass to it as a bare
minimum.

The first prop is the data that accepts a plain array. This array contains the list of items to
display. The second prop is the renderItem. The renderItem takes an item from the data
and renders it into the list.

You can also provide additional metadata like index to the renderItem. Here index is a
number that corresponds to a particular item in the data array.

Now within the MenuItems component, you are going to render the FlatList component as
follows:

const MenuItems = () => {


const renderItem = ({ item }) => <Item name={item.name} />;

return (
<View style={menuStyles.container}>
<Text style={menuStyles.headerText}>View Menu</Text>
<FlatList data={menuItemsToDisplay} keyExtractor={item => item.id} renderIt
em={renderItem}></FlatList>
</View>
);
};
Notice here that you have provided the data prop with the name of the array you already have
defined, which is menuItemsToDisplay. The renderItem method calls a call-back method
which renders another component called Item. You can also see an additional prop called the
keyExtractor being passed to the FlatList component. It instructs the list to use the id of
each item as React keys.

Next you'll define the Item component.

const Item = ({ name }) => (


<View style={menuStyles.innerContainer}>
<Text style={menuStyles.itemText}>{name}</Text>
</View>
);

In the code above, the Item component takes name as the prop. And it renders name within a
parent view. The Item component is rendered for every item in the array until it reaches the end.

And that’s it!

This is a much better way to render large lists performantly than the ScrollView component.
The FlatList renders items lazily, which means it only renders items actually seen on the
screen. Once you start scrolling up or down, those items off the screen are removed, and the new
items are rendered. This form of lazy rendering is very performant and effective when rendering
large lists in mobile apps.
Below, you’ll find the styles used in this component for your reference:

const menuStyles = StyleSheet.create({


container: {
flex: 0.75,
},
innerContainer: {
paddingHorizontal: 40,
paddingVertical: 20,
backgroundColor: 'black',
},
headerText: {
color: 'white',
fontSize: 40,
flexWrap: 'wrap',
textAlign: 'center',
},
itemText: {
color: '#F4CE14',
fontSize: 36,
},
});

export default MenuItems;


Putting it all together
import { View, Text, StyleSheet, FlatList } from 'react-native';

const menuItemsToDisplay = [
{ name: 'Hummus', id: '1A' },
{ name: 'Moutabal', id: '2B' },
{ name: 'Falafel', id: '3C' },
{ name: 'Marinated Olives', id: '4D' },
{ name: 'Kofta', id: '5E' },
{ name: 'Eggplant Salad', id: '6F' },
{ name: 'Lentil Burger', id: '7G' },
{ name: 'Smoked Salmon', id: '8H' },
{ name: 'Kofta Burger', id: '9I' },
{ name: 'Turkish Kebab', id: '10J' },
{ name: 'Fries', id: '11K' },
{ name: 'Buttered Rice', id: '12L' },
{ name: 'Bread Sticks', id: '13M' },
{ name: 'Pita Pocket', id: '14N' },
{ name: 'Lentil Soup', id: '15O' },
{ name: 'Greek Salad', id: '16Q' },
{ name: 'Rice Pilaf', id: '17R' },
{ name: 'Baklava', id: '18S' },
{ name: 'Tartufo', id: '19T' },
{ name: 'Tartufo', id: '20U' },
{ name: 'Tiramisu', id: '21V' },
{ name: 'Panna Cotta', id: '22W' },
];

const Item = ({ name }) => (


<View style={menuStyles.innerContainer}>
<Text style={menuStyles.itemText}>{name}</Text>
</View>
);
const Item = ({ name }) => (
<View style={menuStyles.innerContainer}>
<Text style={menuStyles.itemText}>{name}</Text>
</View>
);

const MenuItems = () => {


const renderItem = ({ item }) => <Item name={item.name} />;

return (
<View style={menuStyles.container}>
<Text style={menuStyles.headerText}>View Menu</Text>
<FlatList
data={menuItemsToDisplay}
keyExtractor={(item) => item.id}
renderItem={renderItem}></FlatList>
</View>
);
};

const menuStyles = StyleSheet.create({


container: {
flex: 0.75,
},
innerContainer: {
paddingHorizontal: 40,
paddingVertical: 20,
backgroundColor: 'black',
},
headerText: {
color: 'white',
fontSize: 40,
flexWrap: 'wrap',
textAlign: 'center',
},
itemText: {
color: '#F4CE14',
fontSize: 36,
},
});

export default MenuItems;


You should now be familiar with how to use the FlatList component to render large lists in React
Native efficiently.

Exercise: Render a large list using


FlatList
Overview

1. e 2

2. Exercise: Render a large list using FlatList

PreviousNext

Exercise: Render a large list using


FlatList
Overview
By now, you should be familiar with the FlatList component and how to use it to render large lists.
Recall that FlatList renders items lazily, which means that it only renders items as they're needed
rather than the entire list. This makes it ideal for rendering large lists without slowing down app
performance.

In this exercise, you will update the Little Lemon app to display a large list of menu items and each
item’s price. You will accomplish this by using a FlatList component.

Scenario
The Little Lemon app needs to display a large list of menu items on the screen, along with the price
of each item. You have been asked to use the FlatList component to render these menu items
efficiently. You should also make sure that the component you write is readable and clean.

Below is the array of menu items and the price for each item. Note that each item also has an id
value.

const menuItemsToDisplay = [
{ name: 'Hummus', price: '$5.00', id: '1A' },
{ name: 'Moutabal', price: '$5.00', id: '2B' },
{ name: 'Falafel', price: '$7.50', id: '3C' },
{ name: 'Marinated Olives', price: '$5.00', id: '4D' },
{ name: 'Kofta', price: '$5.00', id: '5E' },
{ name: 'Eggplant Salad', price: '$8.50', id: '6F' },
{ name: 'Lentil Burger', price: '$10.00', id: '7G' },
{ name: 'Smoked Salmon', price: '$14.00', id: '8H' },
{ name: 'Kofta Burger', price: '$11.00', id: '9I' },
{ name: 'Turkish Kebab', price: '$15.50', id: '10J' },
{ name: 'Fries', price: '$3.00', id: '11K' },
{ name: 'Buttered Rice', price: '$3.00', id: '12L' },
{ name: 'Bread Sticks', price: '$3.00', id: '13M' },
{ name: 'Pita Pocket', price: '$3.00', id: '14N' },
{ name: 'Lentil Soup', price: '$3.75', id: '15O' },
{ name: 'Greek Salad', price: '$6.00', id: '16Q' },
{ name: 'Rice Pilaf', price: '$4.00', id: '17R' },
{ name: 'Baklava', price: '$3.00', id: '18S' },
{ name: 'Tartufo', price: '$3.00', id: '19T' },
{ name: 'Tiramisu', price: '$5.00', id: '20U' },
{ name: 'Panna Cotta', price: '$5.00', id: '21V' },
];
You will use this array to render the items within the screen. Also, use the id for each item as
the key to the FlatList component.

The screenshots below demonstrate how your app should look after you complete this exercise:
The colors displayed in the images above can be applied with the following values:

#F4CE14, #EE9972, #333333, #EDEFEE, black and white.

Starter Code
Use the starter code and build upon it to complete this exercise. You can download the code from
this zipped folder:

Instructions
Step 1: Create a component to display menu items and use FlatList

To begin, create a new component to display the menu items and prices. You can call this
component MenuItems.

Create this file within the existing components folder as follows:


components/MenuItems.js

Within this component, use the array menuItemsToDisplay provided in the scenario to pass
to the data prop of the FlatList component.

Then, configure the renderItem prop of the FlatList component to render each item’s
name and the price per item. Provide the id as the key to the FlatList.

Hint: You can create multiple components within the same file to keep code clean.

Step 2: Style the component

Next, you will style the new component you created to match the screenshots shown above. It is
best to do this by adding styles to the StyleSheet, and then calling them within the component.
Make sure to provide meaningful names to all your styles, making them easier to reference later.
For example, headerText is a more useful name than style1.

Hint: You may want to use the following style props: backgroundColor and fontSize.
When using a StyleSheet, don’t forget to define it within the file first by using const.

Step 3: Render the component from App.js

To finish this exercise, you’ll need to render the component you just created so that it renders the
menu items on the screen. Render this component from the App component and check the results
in the emulator to verify that it renders correctly.

Conclusion
By completing this exercise, you will demonstrate your understanding and ability to configure
and utilize the FlatList component in order to render a large list of items.
Explore the SectionList Component
In an earlier video, you learned how to use the SectionList component to render large lists with
section headers efficiently. In this reading, let’s explore the code from that video to build the
SectionList component to display an extensive list of menu items for the Little Lemon app.

The code below contains the list of menu items you want to display on the Little Lemon menu. It is
declared as an array of objects. A title categorizes each menu item. You have four categories:
appetizers, main dishes, sides, and desserts.

Within each category, there is a data array that contains the name of each menu item for that
category.

const menuItemsToDisplay = [
{
title: 'Appetizers',
data: [
'Hummus',
'Moutabal',
'Falafel',
'Marinated Olives',
'Kofta',
'Eggplant Salad',
],
},
{
title: 'Main Dishes',
data: ['Lentil Burger', 'Smoked Salmon', 'Kofta Burger', 'Turkish Kebab'],
},
{
title: 'Sides',
data: [
'Fries',
'Buttered Rice',
'Bread Sticks',
'Pita Pocket',
'Lentil Soup',
'Greek Salad',
'Rice Pilaf',
],
},
{
title: 'Desserts',
data: ['Baklava', 'Tartufo', 'Tiramisu', 'Panna Cotta'],
},
];
To use the SectionList component, you will need to import it directly from the React Native
package since it is a

import { View, Text, StyleSheet, SectionList } from'react-native'

The SectionList component has two required props you will need to pass as a bare
minimum. It is very similar to the FlatList component you learned about in an earlier section
of the course.

The first prop is the sections that accept a plain array. This array contains the list of items to
display. The second required prop is the renderItem. The renderItem takes an item from
the sections and renders it into the list.

Now within the MenuItems component, you should render the SectionList component as
follows:

const MenuItems = () => {


const renderItem = ({ item }) => <Item name={item} />;

const renderSectionHeader = ({ section: { title } }) => (


<Text style={menuStyles.sectionHeader}>{title} </Text>
);

return (
<View style={menuStyles.container}>
<SectionList
keyExtractor={(item, index) => item + index}
sections={menuItemsToDisplay}
renderItem={renderItem}
renderSectionHeader={renderSectionHeader}
</SectionList>
</View>
);
};

Notice here that you have provided the sections prop with the name of the array you already
have defined, which is menuItemsToDisplay. The renderItem method calls a call-back
method which renders another component called Item. You can also see an additional prop, the
keyExtractor being passed to the SectionList component. It tells the list to use each id
as React keys.

Notice there is a renderSectionHeader call-back function passed to the prop as well. This is
used to render each section’s header. These examples would be Appetizers, Main Dishes and so
on. It renders title from the menuItemsToDisplay array.

Let’s define the Item component next:

const Item = ({ name }) => (


<View style={menuStyles.innerContainer}>
<Text style={menuStyles.itemText}>{name}</Text>
</View>
);

In the above code, the Item component takes name as the prop and it renders name within a
parent view. The Item component is rendered for every item in the array until it reaches the end.

You can enhance your SectionList component with separators and footers if you want. They
are passed to the component via the ListFooterComponent prop and the
ItemSeparatorComponent prop as shown below:

const MenuItems = () => {


const renderItem = ({ item }) => <Item name={item} />;

const renderSectionHeader = ({ section: { title } }) => (


<Text style={menuStyles.sectionHeader}>{title} </Text>
);

return (
<View style={menuStyles.container}>
<SectionList
keyExtractor={(item, index) => item + index}
sections={menuItemsToDisplay}
renderItem={renderItem}
renderSectionHeader={renderSectionHeader}
ListFooterComponent={Footer}
ItemSeparatorComponent={Separator}></SectionList>
</View>
);
};

Below you'll find the component code for the separator and footer:
const Separator = () => <View style={menuStyles.separator} />;

const Footer = () => (


<Text style={menuStyles.footerText}>
All Rights Reserved by Little Lemon 2022
</Text>
);

And that’s it!

The SectionList renders items lazily, which means it only renders items you visually see on
the screen, and once you start scrolling up or down, those items off the screen are removed, and
the new items are rendered. This form of lazy rendering is very performant and effective in
rendering large lists with sectional support in mobile apps.
Below are the styles used in this component for your reference:

const menuStyles = StyleSheet.create({


container: {
flex: 0.95,
},
innerContainer: {
paddingHorizontal: 40,
paddingVertical: 20,
backgroundColor: '#333333',
},
sectionHeader: {
backgroundColor: '#fbdabb',
color: '#333333',
fontSize: 34,
flexWrap: 'wrap',
textAlign: 'center',
},
itemText: {
color: '#F4CE14',
fontSize: 32,
},
separator: {
borderBottomWidth: 1,
borderColor: '#EDEFEE',
},
footerText: {
color: '#EDEFEE',
fontSize: 20,
flexWrap: 'wrap',
textAlign: 'center',
},
});
Putting it all together below is the entire MenuItems component that displays the lists by sections.

import React from 'react';

import { View, Text, StyleSheet, SectionList } from 'react-native';

const menuItemsToDisplay = [
{
title: 'Appetizers',
data: [
'Hummus',
'Moutabal',
'Falafel',
'Marinated Olives',
'Kofta',
'Eggplant Salad',
],
},
{
title: 'Main Dishes',
data: ['Lentil Burger', 'Smoked Salmon', 'Kofta Burger', 'Turkish Kebab'],
},
{
title: 'Sides',
data: [
'Fries',
'Buttered Rice',
'Bread Sticks',
'Pita Pocket',
'Lentil Soup',
'Greek Salad',
'Rice Pilaf',
],
},
{
title: 'Desserts',
data: ['Baklava', 'Tartufo', 'Tiramisu', 'Panna Cotta'],
},
];

const Item = ({ name }) => (


<View style={menuStyles.innerContainer}>
<Text style={menuStyles.itemText}>{name}</Text>
</View>
);

In this section, you learned how to use the SectionList component to render large lists with
section headers in React Native efficiently.

Exercise: Render a large list using


SectionList
Overview
So far, you have learned about the FlatList and SectionList components and how to render
large lists using them. You’ve discovered that while FlatList is useful for rendering large lists
performantly, SectionList adds the ability to separate list items into sections.

In this exercise, you will expand on the example from an earlier exercise to display a large list of
menu items with each item’s price. You will use the SectionList component within the Little
Lemon app.

By doing this, each menu item will be categorized according to its item type and will display section
headers such as Appetizers, Main dishes and so on.

Scenario
The Little Lemon app needs to display a large list of menu items on the screen, along with the price
of each item, sorted into sections. You have been asked to use the SectionList component to
render these menu items efficiently. Make sure that the component you write is readable and clean.

Below is the array of menu items, along with the price for each item

const menuItemsToDisplay = [
{
title: 'Appetizers',
data: [
{ name: 'Hummus', price: '$5.00' },
{ name: 'Moutabal', price: '$5.00' },
{ name: 'Falafel', price: '$7.50' },
{ name: 'Marinated Olives', price: '$5.00' },
{ name: 'Kofta', price: '$5.00' },
{ name: 'Eggplant Salad', price: '$8.50' },
],
},
{
title: 'Main Dishes',
data: [
{ name: 'Lentil Burger', price: '$10.00' },
{ name: 'Smoked Salmon', price: '$14.00' },
{ name: 'Kofta Burger', price: '$11.00' },
{ name: 'Turkish Kebab', price: '$15.50' },
],
},
{
title: 'Sides',
data: [
{ name: 'Fries', price: '$3.00', id: '11K' },
{ name: 'Buttered Rice', price: '$3.00' },
{ name: 'Bread Sticks', price: '$3.00' },
{ name: 'Pita Pocket', price: '$3.00' },
{ name: 'Lentil Soup', price: '$3.75' },
{ name: 'Greek Salad', price: '$6.00' },
{ name: 'Rice Pilaf', price: '$4.00' },
],
},
{
title: 'Desserts',
data: [
{ name: 'Baklava', price: '$3.00' },
{ name: 'Tartufo', price: '$3.00' },
{ name: 'Tiramisu', price: '$5.00' },
{ name: 'Panna Cotta', price: '$5.00' },
],
},
];

Use this array to render the items within the screen.

The screenshots below illustrate how your app should look after you complete this exercise:
The colors displayed in the images above can be applied using the following values:
#F4CE14, #EE9972, #333333, #EDEFEE, black and white.

Starter Code:

You can download the starter code for this exercise, from the zipped folder below:

Instructions
Step 1: Update MenuItems component to display new list of menu items and use
SectionList

To complete this exercise, you’ll first need to update the MenuItems component to display the
menu items and price.

Within this component, use the array provided in this scenario to pass to the data prop of the
SectionList component. Then configure the renderItem prop of the SectionList
component to render each item’s name as well as the price per item.

Hint: You can create multiple components within the same file to keep code clean.

Step 2: Render Section Header

In this step, you will use the SectionList component to render the section header. The
headers are provided within the title property in the array menuItemsToDisplay. Utilize it
to render the headers for each section of menu items. Make sure that each menu item is now
displayed inside the appropriate section.

Step 3: Style the component

In this step, you will style the new component that you have created to match the screenshots.
Make sure to provide meaningful names to all your styles.

Conclusion
By completing this exercise, you will demonstrate your understanding and ability to configure
and utilize the SectionList component to render a large list of items by section.

Solution: Render a large list using


SectionList
Overview
In this reading, you will review the solution code for the exercise.
The code block below outlines the outcome of the exercise in its entirety.

MenuItems.js

import React from 'react';

import { View, Text, StyleSheet, SectionList } from 'react-native';

const menuItemsToDisplay = [
{
title: 'Appetizers',
data: [
{ name: 'Hummus', price: '$5.00' },
{ name: 'Moutabal', price: '$5.00' },
{ name: 'Falafel', price: '$7.50' },
{ name: 'Marinated Olives', price: '$5.00' },
{ name: 'Kofta', price: '$5.00' },
{ name: 'Eggplant Salad', price: '$8.50' },
],
},
{
title: 'Main Dishes',
data: [
{ name: 'Lentil Burger', price: '$10.00' },
{ name: 'Smoked Salmon', price: '$14.00' },
{ name: 'Kofta Burger', price: '$11.00' },
{ name: 'Turkish Kebab', price: '$15.50' },
],
},
{
title: 'Sides',
data: [
{ name: 'Fries', price: '$3.00', id: '11K' },
{ name: 'Buttered Rice', price: '$3.00' },
{ name: 'Bread Sticks', price: '$3.00' },
{ name: 'Pita Pocket', price: '$3.00' },
{ name: 'Lentil Soup', price: '$3.75' },
{ name: 'Greek Salad', price: '$6.00' },
{ name: 'Rice Pilaf', price: '$4.00' },
],
},
{
title: 'Desserts',
data: [
{ name: 'Baklava', price: '$3.00' },
{ name: 'Tartufo', price: '$3.00' },
{ name: 'Tiramisu', price: '$5.00' },
{ name: 'Panna Cotta', price: '$5.00' },
],
},
];

const Item = ({ name, price }) => (


<View style={menuStyles.innerContainer}>
<Text style={menuStyles.itemText}>{name}</Text>
<Text style={menuStyles.itemText}>{price}</Text>
</View>
);

const MenuItems = () => {


const renderItem = ({ item }) => <Item name={item.name} price={item.price} />;

const renderSectionHeader = ({ section: { title } }) => (


<View style={menuStyles.headerStyle}>
<Text style={menuStyles.sectionHeader}>{title}</Text>
</View>
);

return (
<View style={menuStyles.container}>
<SectionList
sections={menuItemsToDisplay}
keyExtractor={(item, index) => item + index}
renderItem={renderItem}
renderSectionHeader={renderSectionHeader}></SectionList>
</View>
);
};

const menuStyles = StyleSheet.create({


container: {
flex: 1,
},
innerContainer: {
paddingHorizontal: 40,
paddingVertical: 20,
flexDirection: 'row',
justifyContent: 'space-between',
},
itemText: {
color: '#F4CE14',
fontSize: 20,
},
headerStyle: {
backgroundColor: '#F4CE14',
},
sectionHeader: {
color: 'black',
fontSize: 26,
flexWrap: 'wrap',
textAlign: 'center',
},
});

export default MenuItems;


App.js

import * as React from 'react';


import { View, StyleSheet } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import LittleLemonFooter from './components/LittleLemonFooter';
import MenuItems from './components/MenuItems';

export default function App() {


return (
<>
<View style={styles.container}>
<LittleLemonHeader />
<MenuItems />
</View>
<View style={styles.footerContainer}>
<LittleLemonFooter />
</View>
</>
);
}

const styles = StyleSheet.create({


container: {
flex: 1,
backgroundColor: '#333333',
},
footerContainer: { backgroundColor: '#333333' },
});
import * as React from 'react';
import { View, StyleSheet } from 'react-native';

import LittleLemonHeader from './components/LittleLemonHeader';


import LittleLemonFooter from './components/LittleLemonFooter';
import MenuItems from './components/MenuItems';

export default function App() {


return (
<>
<View style={styles.container}>
<LittleLemonHeader />
<MenuItems />
</View>
<View style={styles.footerContainer}>
<LittleLemonFooter />
</View>
</>
);
}

const styles = StyleSheet.create({


container: {
flex: 1,
backgroundColor: '#333333',
},
footerContainer: { backgroundColor: '#333333' },
});
Procedure
Next, review the breakdown of the individual steps below.

Step 1: Update the MenuItems component to use SectionList

Within the existing MenuItems component, render the SectionList component instead of
FlatList and pass to it the array from this scenario as shown below.

Make sure to use the updated array!

import React from 'react';

import { View, Text, SectionList } from 'react-native';

const menuItemsToDisplay = [
{
title: 'Appetizers',
data: [
{ name: 'Hummus', price: '$5.00' },
{ name: 'Moutabal', price: '$5.00' },
{ name: 'Falafel', price: '$7.50' },
{ name: 'Marinated Olives', price: '$5.00' },
{ name: 'Kofta', price: '$5.00' },
{ name: 'Eggplant Salad', price: '$8.50' },
],
},
{
title: 'Main Dishes',
data: [
{ name: 'Lentil Burger', price: '$10.00' },
{ name: 'Smoked Salmon', price: '$14.00' },
{ name: 'Kofta Burger', price: '$11.00' },
{ name: 'Turkish Kebab', price: '$15.50' },
],
},
{
title: 'Sides',
data: [
{ name: 'Fries', price: '$3.00', id: '11K' },
{ name: 'Buttered Rice', price: '$3.00' },
{ name: 'Bread Sticks', price: '$3.00' },
{ name: 'Pita Pocket', price: '$3.00' },
{ name: 'Lentil Soup', price: '$3.75' },
{ name: 'Greek Salad', price: '$6.00' },
{ name: 'Rice Pilaf', price: '$4.00' },
],
},
{
title: 'Desserts',
data: [
{ name: 'Baklava', price: '$3.00' },
{ name: 'Tartufo', price: '$3.00' },
{ name: 'Tiramisu', price: '$5.00' },
{ name: 'Panna Cotta', price: '$5.00' },
],
},
];

const Item = ({ name, price }) => (


<View>
<Text>{name}</Text>
<Text>{price}</Text>
</View>
);

const MenuItems = () => {


const renderItem = ({ item }) => <Item name={item.name} price={item.price} />;

return (
<View>
<SectionList
sections={menuItemsToDisplay}
keyExtractor={(item, index) => item + index}
renderItem={renderItem}></SectionList>
</View>
);
};

export default MenuItems;


Step 2: Render Section Header

Render the section headers using the code below.

const menuItemsToDisplay = [
{
title: 'Appetizers',
data: [
{ name: 'Hummus', price: '$5.00' },
{ name: 'Moutabal', price: '$5.00' },
{ name: 'Falafel', price: '$7.50' },
{ name: 'Marinated Olives', price: '$5.00' },
{ name: 'Kofta', price: '$5.00' },
{ name: 'Eggplant Salad', price: '$8.50' },
],
},
{
title: 'Main Dishes',
data: [
{ name: 'Lentil Burger', price: '$10.00' },
{ name: 'Smoked Salmon', price: '$14.00' },
{ name: 'Kofta Burger', price: '$11.00' },
{ name: 'Turkish Kebab', price: '$15.50' },
],
},
{
title: 'Sides',
data: [
{ name: 'Fries', price: '$3.00', id: '11K' },
{ name: 'Buttered Rice', price: '$3.00' },
{ name: 'Bread Sticks', price: '$3.00' },
{ name: 'Pita Pocket', price: '$3.00' },
{ name: 'Lentil Soup', price: '$3.75' },
{ name: 'Greek Salad', price: '$6.00' },
{ name: 'Rice Pilaf', price: '$4.00' },
],
},
{
title: 'Desserts',
data: [
{ name: 'Baklava', price: '$3.00' },
{ name: 'Tartufo', price: '$3.00' },
{ name: 'Tiramisu', price: '$5.00' },
{ name: 'Panna Cotta', price: '$5.00' },
],
},
];

const Item = ({ name, price }) => (


<View>
<Text>{name}</Text>
<Text>{price}</Text>
</View>
);

const MenuItems = () => {


const renderItem = ({ item }) => <Item name={item.name} price={item.price} />;

// Add section header


const renderSectionHeader = ({ section: { title } }) => (
<View>
<Text>{title}</Text>
</View>
);

return (
<View>
<SectionList
sections={menuItemsToDisplay}
keyExtractor={(item, index) => item + index}
renderItem={renderItem}
renderSectionHeader={renderSectionHeader}></SectionList>
</View>
);
};

export default MenuItems;


Step 3: Style the component

Once you have coded a working component, it is time to style it. In this step, you will style the
MenuItems component to match the screenshots displayed above.

import React from 'react';

import { View, Text, StyleSheet, SectionList } from 'react-native';

const menuItemsToDisplay = [
{
title: 'Appetizers',
data: [
{ name: 'Hummus', price: '$5.00' },
{ name: 'Moutabal', price: '$5.00' },
{ name: 'Falafel', price: '$7.50' },
{ name: 'Marinated Olives', price: '$5.00' },
{ name: 'Kofta', price: '$5.00' },
{ name: 'Eggplant Salad', price: '$8.50' },
],
},
{
title: 'Main Dishes',
data: [
{ name: 'Lentil Burger', price: '$10.00' },
{ name: 'Smoked Salmon', price: '$14.00' },
{ name: 'Kofta Burger', price: '$11.00' },
{ name: 'Turkish Kebab', price: '$15.50' },
],
},
{
title: 'Sides',
data: [
{ name: 'Fries', price: '$3.00', id: '11K' },
{ name: 'Buttered Rice', price: '$3.00' },
{ name: 'Bread Sticks', price: '$3.00' },
{ name: 'Pita Pocket', price: '$3.00' },
{ name: 'Lentil Soup', price: '$3.75' },
{ name: 'Greek Salad', price: '$6.00' },
{ name: 'Rice Pilaf', price: '$4.00' },
],
},
{
title: 'Desserts',
data: [
{ name: 'Baklava', price: '$3.00' },
{ name: 'Tartufo', price: '$3.00' },
{ name: 'Tiramisu', price: '$5.00' },
{ name: 'Panna Cotta', price: '$5.00' },
],
},
];

const Item = ({ name, price }) => (


<View style={menuStyles.innerContainer}>
<Text style={menuStyles.itemText}>{name}</Text>
<Text style={menuStyles.itemText}>{price}</Text>
</View>
);

const MenuItems = () => {


const renderItem = ({ item }) => <Item name={item.name} price={item.price} />;

const renderSectionHeader = ({ section: { title } }) => (


<View style={menuStyles.headerStyle}>
<Text style={menuStyles.sectionHeader}>{title}</Text>
</View>
);

return (
<View style={menuStyles.container}>
<SectionList
sections={menuItemsToDisplay}
keyExtractor={(item, index) => item + index}
renderItem={renderItem}
renderSectionHeader={renderSectionHeader}></SectionList>
</View>
);
};

const menuStyles = StyleSheet.create({


container: {
flex: 1,
},
innerContainer: {
paddingHorizontal: 40,
paddingVertical: 20,
flexDirection: 'row',
justifyContent: 'space-between',
},
itemText: {
color: '#F4CE14',
fontSize: 20,
},
headerStyle: {
backgroundColor: '#F4CE14',
},
sectionHeader: {
color: 'black',
fontSize: 26,
flexWrap: 'wrap',
textAlign: 'center',
},
});

export default MenuItems;


TextInput Component and its Features
In this reading, you will explore the code to create a feedback form for the Little Lemon app. In an
earlier video, you saw how it was done, and in this reading, you will explore the code in detail.

The feedback form will accept the user’s input via the virtual keyboard. To do this, React Native
provides the TextInput component out-of-the-box.

Import:
Let’s go ahead and import the TextInput component, as shown below, along with the other
necessary imports:

import React, { useState } from 'react';

import { ScrollView, StyleSheet, Text, TextInput } from 'react-native';

Note that you will have to import the useState hook as well. This will be used to keep track of the
local state of all the user inputs within the feedback form.

Setting local state:


The next step is to set up the state variables within the new FeedbackForm component. The
default value for all these state variables will be an empty string.

const [firstName, onChangeFirstName] = useState('');


const [lastName, onChangeLastName] = useState('');
const [message, onChangeMessage] = useState('');

Configure Text Input


The next step is to configure the TextInput component. You will be rendering three text
inputs for each box: first name, last name, and the message.

You will pass a style, value, and onChangeText prop to each text input. The value here
represents what the user is typing within the box, and it is the current value of the local state
variable of that box. The onChangeText prop will call back the set state method of each of the
local state variables.

For instance, for the first name, the onChangeText will get triggered as the user is typing, and
it will call the onChangeFirstName method and set the new or updated text to the
firstName variable.

<TextInput
style={styles.input}
value={firstName}
onChangeText={onChangeFirstName}
/>
<TextInput
style={styles.input}
value={lastName}
onChangeText={onChangeLastName}
/>
<TextInput
style={styles.messageInput}
value={message}
onChangeText={onChangeMessage}
/>
Similarly, you can also use the same pattern to set up the other text input boxes.

Putting it all together:


import React, { useState } from 'react';
import { ScrollView, StyleSheet, Text, TextInput } from 'react-native';

const FeedbackForm = () => {


// declare the variables
const [firstName, onChangeFirstName] = useState('');
const [lastName, onChangeLastName] = useState('');
const [message, onChangeMessage] = useState('');
const [phoneNumber, onChangePhoneNumber] = useState('');

return (
<ScrollView style={styles.container}>
<Text style={styles.headingSection}>
How was your visit to Little Lemon?
</Text>
<Text style={styles.infoSection}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear your experience with us!
</Text>
<TextInput
style={styles.input}
value={firstName}
onChangeText={onChangeFirstName}
/>
<TextInput
style={styles.input}
value={lastName}
onChangeText={onChangeLastName}
/>
<TextInput
style={styles.messageInput}
value={message}
onChangeText={onChangeMessage}
/>
</ScrollView>
);
};

const styles = StyleSheet.create({


container: {
flex: 1,
},
input: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
fontSize: 16,
borderColor: 'EDEFEE',
backgroundColor: '#F4CE14',
},
messageInput: {
height: 100,
margin: 12,
borderWidth: 1,
padding: 10,
fontSize: 16,
backgroundColor: '#F4CE14',
},
infoSection: {
fontSize: 24,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
backgroundColor: '#495E57',
},
headingSection: {
fontSize: 28,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
backgroundColor: '#495E57',
},
});

export default FeedbackForm;


And there you go!

In this reading you learned how to configure and use the TextInput component to build a
feedback form for the Little Lemon app.

Exercise: Create a TextInput Component


Overview
You should now be familiar with what the TextInput component is and how to use it. Recall that
TextInput is a built-in component that enables users to input text to a React Native app using a
keyboard.

In this exercise, you will create a sample text input box in the Little Lemon app that enters the user’s
name.

Scenario
For this exercise, your task is configuring a text input box on the Welcome screen, where the user
can enter their name. The input box should contain placeholder text, and the text that is input should
be stored in the local state.

Starter code
You can download the starter code from the zipped folder below:
The colors displayed in the images above can be applied using the following values:

#EDEFEE, black and white.

Instructions
Step 1: Configure TextInput component on the Welcome Screen.

Your first step in this exercise is to configure the TextInput component on the Welcome
Screen. It will accept the user’s input.

Make sure to import the TextInput component from React Native and provide it with the
value and onChangeText props.

Step 2: Store user input within TextInput as local state

In this step, you will store what the user types within the component’s local state.

Hint: You’ll need to make use of the useState hook to accomplish this.

Step 3: Style the component

In this step, you will style the new component that you created to match the screenshots. Make
sure to provide meaningful names to all your styles.

Hint: Style the text input box by providing appropriate height, margin, padding, border width
and font size. You can play around with different styles here to get the desired outcome, so be
creative!

Conclusion
By completing this exercise, you will demonstrate your understanding and ability to configure
and utilize the TextInput component to accept user’s input within a text box.

Solution: Create a TextInput Component


Overview
In this reading, you will review the solution code for the exercise.

The code block below outlines the outcome of the exercise in its entirety.

WelcomeScreen.js

import React, { useState } from 'react';


import { ScrollView, Text, StyleSheet, TextInput } from 'react-native';

export default function WelcomeScreen() {


const [firstName, onChangeFirstName] = useState('');
return (
<ScrollView style={styles.container}>
<Text style={styles.headerText}>Welcome to Little Lemon</Text>
<Text style={styles.regularText}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear more about your experience with us!
</Text>
<TextInput
style={styles.inputBox}
value={firstName}
onChangeText={onChangeFirstName}
placeholder={'First Name'}
/>
</ScrollView>
);
}

const styles = StyleSheet.create({


container: {
flex: 1,
},
headerText: {
padding: 40,
fontSize: 30,
color: '#EDEFEE',
textAlign: 'center',
},
regularText: {
fontSize: 24,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
},
inputBox: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
fontSize: 16,
borderColor: 'EDEFEE',
backgroundColor: '#EDEFEE',
},
});

The code above will produce the following output on the emulator:
Procedure
Next, review the breakdown of the individual steps below.

Step 1: Configure TextInput component on the Welcome Screen.

On the Welcome Screen, configure the TextInput component to accept user’s input.

First, import TextInput from React Native:

import { ScrollView, Text, StyleSheet, TextInput } from 'react-native';

Then, configure the TextInput component:

<TextInput
value={firstName}
onChangeText={onChangeFirstName}
placeholder={'First Name'}
/>

Step 2: Store user input within TextInput as local state

In this step, make sure to import the useState hook from React and create a local state for
storing the user’s name that is being entered in the text input box.

import React, { useState } from 'react';

const [firstName, onChangeFirstName] = useState('');

Step 3: Style the component

Once you have coded a working component, it is time to style it. In this step, you will style the
TextInput component to match the screenshots above.

import React, { useState } from 'react';


import { ScrollView, Text, StyleSheet, TextInput } from 'react-native';

export default function WelcomeScreen() {


return (
<ScrollView style={styles.container}>
<Text style={styles.headerText}>Welcome to Little Lemon</Text>
<Text style={styles.regularText}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would love
to hear your experience with us!
</Text>
<TextInput
style={styles.inputBox}
value={firstName}
onChangeText={onChangeFirstName}
placeholder={'First Name'}
/>
</ScrollView>
);

const styles = StyleSheet.create({


container: {
flex: 1,
},
headerText: {
padding: 40,
fontSize: 30,
color: '#EDEFEE',
textAlign: 'center',
},
regularText: {
fontSize: 24,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
},
inputBox: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
fontSize: 16,
borderColor: 'EDEFEE',
backgroundColor: '#EDEFEE',
},
});

Tips and Tricks to handle the virtual


keyboard
This reading will teach you some tips and tricks for handling the virtual keyboard. You observed in
an earlier video how the virtual keyboard can be tackled efficiently. In this reading, you will explore
the code for it in detail.

keyboardDismissMode
A common problem you will encounter while developing React Native apps is that the virtual
keyboard within a ScrollView will be constantly visible while you scroll through a page. You would
have to tap outside of the text input and dismiss it. This could get annoying to the user. Instead, you
can provide a seamless user experience by applying the keyboardDismissMode prop within your
ScrollView component.

Setting the prop value to on-drag will ensure the keyboard is dismissed when you start scrolling or
dragging on the screen. This will be seamless for the user, who can always tap back on the text
input box to open up the virtual keyboard again.

<ScrollView keyboardDismissMode="on-drag">
{/* Text inputs and other code ...

...

/*}
</ScrollView >

The keyboardDismissMode prop by default has the value none, which means the drags do not
dismiss the keyboard.
KeyboardAvoidingView
Another handy component for managing the virtual keyboard is the KeyboardAvoidingView.
As the name suggests, it is a component that automatically adjusts its height, position, or bottom
padding based on the keyboard’s height so that it remains visible. In contrast, the virtual
keyboard is still displayed. This component is part of the core react-native package and can
be imported directly as follows:

import { KeyboardAvoidingView } from 'react-native';

While using this component, you can set specific properties depending on whether it is an iOS or
Android device. To determine that, you can use the Platform API, also available within React
Native.

import { Platform } from 'react-native';

Configuring KeyboardAvoidingView
This component inherits all the props of View, making it essentially View with additional
capabilities. Within the KeyboardAvoidingView component, you can pass the behavior
prop. This prop determines how to react to the presence of the keyboard. Depending on the use
case, three values can be passed to it: height, position and padding.

In this example, you can see how the Platform API sets the behavior value to padding for
iOS devices and, height for all other devices.

<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>

{/* Text inputs and other code ...

...

/*}
</KeyboardAvoidingView>

Putting it all together


Finally, let’s find out how your code might look once you’ve applied both
keyboardDismissMode and KeyboardAvoidingView together.

import React, { useState } from 'react';


import {
StyleSheet,
Text,
TextInput,
ScrollView,
KeyboardAvoidingView,
Platform,
} from 'react-native';

const FeedbackForm = () => {


// declare the variables
const [firstName, onChangeFirstName] = useState('');
const [lastName, onChangeLastName] = useState('');
const [message, onChangeMessage] = useState('');

return (
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}>
<ScrollView keyboardDismissMode="on-drag">
<Text style={styles.headingSection}>
How was your visit to Little Lemon?
</Text>
<Text style={styles.infoSection}>
Little Lemon is a charming neighborhood bistro that serves simple food
and classic cocktails in a lively but casual environment. We would
love to hear your experience with us!
</Text>
<TextInput
style={styles.input}
value={firstName}
onChangeText={onChangeFirstName}
/>
<TextInput
style={styles.input}
value={lastName}
onChangeText={onChangeLastName}
/>
<TextInput
style={styles.messageInput}
value={message}
onChangeText={onChangeMessage}
/>
</ScrollView>
</KeyboardAvoidingView>
);
};

const styles = StyleSheet.create({


container: {
flex: 1,
},
input: {
height: 40,
margin: 12,
borderWidth: 1,
padding: 10,
fontSize: 16,
borderColor: 'EDEFEE',
backgroundColor: '#F4CE14',
},
messageInput: {
height: 100,
margin: 12,
borderWidth: 1,
padding: 10,
fontSize: 16,
backgroundColor: '#F4CE14',
},
infoSection: {
fontSize: 24,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
backgroundColor: '#495E57',
},
headingSection: {
fontSize: 28,
padding: 20,
marginVertical: 8,
color: '#EDEFEE',
textAlign: 'center',
backgroundColor: '#495E57',
},
});

export default FeedbackForm;

In this reading, you explored some tips and tricks to handle the virtual keyboard in React Native
effectively.

You might also like