SlideShare a Scribd company logo
1 of 31
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Cross-platform application development
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Chapter 5: Component In React Navite
 Core Component
 Navigation
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
What are components?
 Components are an abstraction layer on top of the underlying native platform. On an
iOS device, a React Native component is ultimately rendered as a UIView. On
Android, the same component would be rendered as an android.view. As React
Native expands to new platforms, the same code should be able to render correctly
on more and more devices.
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
View Component
 Views are the most basic building block of React Native apps. The View is an
abstraction layer on top of the target platform's native equivalent
• For iOS - UIView
• For Android - android.view
• For Web - <div>
 View is designed to be nested inside other views and can have 0 to many children of
any type
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
View Component
 There are two fairly distinct things we use View for:
• First, we use View for layout. A View is commonly used as a container for other
components. If we want to arrange a group of components vertically or horizontally,
we will likely wrap those components in a View.
• Second, we use View for styling our app. If we want to render a simple shape like
a circle or rectangle, or if we want to render a border, a line, or a background color,
we will likely use a View.
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
 Ex:
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Text Component
 We use the Text component to render text on the screen. Text can be styled with font-
specific attributes such as fontSize. It can use nearly all of the same styles as View,
such as backgroundColor and width. However, Text has some key differences when it
comes to layout.
 Text context will automatically wrap around by default when it fills the width of the
component
Text dimensions
 Unlike the View component, Text components have an intrinsic size
 Ex:
<Text style={{ backgroundColor: 'red', width: 60, height: 60 }}>
Hello World
</Text>
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Text Component
Common Text props and styles
 color - A string representing the color of the text.
 fontFamily - A string with the name of the font family (this font family must already
exist on the device).
 fontSize - A number value equal to the size of the font in points.
 fontStyle - Either 'normal' or 'italic’.
 fontWeight - The thickness of each character. One of 'normal', 'bold', '100', '200',
'300’, '400', '500', '600', '700', '800', or '900'. If the chosen weight isn’t available on the
device, the nearest available weight will be used instead).
 textAlign - The text alignment. One of 'left', 'right', 'center', 'justify' (iOS only), 'auto'.
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Text Component
Common Text props and styles
 numberOfLines - The number of lines to allow before truncating the text.
 ellipsizeMode - How text should be truncated when it exceeds numberOfLines. One
of 'head’, 'middle', 'tail', 'clip' (iOS only).
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Touchable Opacity
 The TouchableOpacity component is similar to View, but lets us easily respond to tap
gestures in a performant way
 One minor inconvenience with both TouchableOpacity and TouchableHighlight: these
components can only have a single child element, so if we want multiple children,
we will need to wrap them in a View
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Image
 Image component to render images on the screen
 There are 3 ways to include images in an app: we can bundle an image asset with
our code (which will then get stored on the device), we can download an image from
a URI or even from data provided in the 'data:' uri scheme.
Bundling image assets
• To bundle an image asset, we can require the image by name from our project
directory just like any other file
<Image source={require('./foo.png')} />
Remote image assets
• To display an image from a URI, we must pass an object to the source prop of the
Image component
<Image source={{ uri: 'https://abc.com/images/img.jpg' }} />
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Image
Use data provided in the 'data:' uri scheme
<Image
style={styles.logo}
source={{
uri:
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQ
BwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgY
GBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==',
}}
/>
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Image
 Common image styles
 resizeMode style (or prop – both work) to determine how the image is cropped in the case
where the image data’s intrinsic dimensions are different than the dimensions of the Image
component
• cover: The image scales uniformly to fill the Image component. The image will be
cropped by the bounding box of the component if they have different aspect ratios.
• contain: The image scales uniformly to fit within the component. The component’s
background color will show if they have different aspect ratios.
• stretch: The image stretches to fill the component.
• repeat: The image repeats itself at its intrinsic dimensions to fill the component (iOS-
only).
• center: The image maintains its intrinsic dimensions, and is centered within the
component.
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Activity Indicator
 We can render a loading indicator using the ActivityIndicator component.
 This component accepts all the same props as View, plus a few more:
• animating: A bool indicating whether to show or hide the indicator (defaults to true).
• color: The color of the spinner (defaults to gray).
• size: One of 'small' or 'large' (defaults to small).
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Activity Indicator
 Ex:
const [loading, setloading] = useState(true);
<View>
{loading && (
<ActivityIndicator size={'large'} />
)}
</View>
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Core Component
Flat List Component
 FlatList components are used for rendering large quantities of scrollable content.
Instead of rendering a children prop, the FlatList renders each item in an input data
array using the renderItem prop
 The renderItem prop is a function which takes an item from the data array and maps
it to a React Element
 Ex:
• https://reactnative.dev/docs/flatlist
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Practice
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
What is navigation?
 One of the primary navigation patterns in a mobile app is a stack-based pattern. In
this pattern, only one screen can be seen by the user at any given time. Navigating
involves pushing the new screen onto the navigation stack
Native navigation (IOS)
 In an iOS application, views are used to build the UI and display content to the user. A
view controller (or the UIViewController class) is used to control a set of views and
allows us to connect our UI with our application data.
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
Native navigation (IOS)
 A navigation controller (UINavigationController ) simplifies the process of navigating
between screens by allowing us to pass in a stack of UIViewControllers. It will take
care of including a header navigation bar at the top of our device with a back button
that allows us to pop the current view controller off of the current stack
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
Native navigation (IOS)
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
Native navigation (Android)
 In Android, activities are used to create single screens to define our UI. We can use
tasks in order to define a stack of activities known as the back stack
 The startActivity method can be used to start a new activity
 When this happens, the activity is pushed onto the activity stack. In order to return
to the previous screen, the physical back button on every Android device can be
pressed in order to run the finish method on the activity. This closes the current
activity, pops it off the stack and returns the user back to the previous activity.
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
Native navigation (Android)
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
React Navigation
 Install: npm install @react-navigation/native-stack
 In both iOS and Android, a back button at the top of the navigation bar is how a user
usually navigates back to a previous screen by removing the current screen off the
stack.
 On Android devices, there is also a physical or soft key back button at the bottom of
the device screen that also allows you to go back on any application.
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
React Navigation
Creating a native stack navigator
 createNativeStackNavigator is a function that returns an object containing 2
properties: Screen and Navigator. Both of them are React components used for
configuring the navigator. The Navigator should contain Screen elements as its
children to define the configuration for routes.
 NavigationContainer is a component which manages our navigation tree and contains
the navigation state
Moving between screens
 Navigating to a new screen
• navigation.navigate()
 Navigate to a route multiple times
• navigation.push()
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
React Navigation
Moving between screens
 Going back
• navigation.goBack()
• Another alternative would be navigation.popToTop(), which goes back to the first
screen in the stack.
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
React Navigation
 Demo
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
React Navigation
Passing parameters to routes
 There are two pieces to this:
• Pass params to a route by putting them in an object as a second parameter to the
navigation.navigate function: navigation.navigate('RouteName', { /* params go here
*/ })
• Read the params in your screen component: route.params.
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
React Navigation
Passing parameters to routes
 Passing params to a previous screen
• use the navigate method, which acts like goBack if the screen already exists. You
can pass the params with navigate to pass the data back
• and use property merge: true
<Button
title="Done"
onPress={() => {
// Pass and merge params back to home screen
navigation.navigate({
name: 'Home',
params: { post: postText },
merge: true,
});
}}
/>
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
React Navigation
Configuring the header bar
<Stack.Navigator>
<Stack.Screen
name="Home“ component={HomeScreen}
options={{
title: 'My home',
headerStyle: {
backgroundColor: '#f4511e',
}, headerTintColor: '#fff',
headerTitleStyle: { fontWeight: 'bold’, },
}}
/>
</Stack.Navigator>
Trường Đại học Xây dựng Hà Nội
Bộ môn Khoa học Máy tính
Navigation
React Navigation
Sharing common options across screens
<Stack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: { fontWeight: 'bold’, },
}}
>
<Stack.Screen
name="Home" component={HomeScreen} options={{ title: 'My home' }}
/>
</Stack.Navigator>

More Related Content

Similar to 6. Chapter 5 - Component In React Navite.pptx

Similar to 6. Chapter 5 - Component In React Navite.pptx (20)

Chapter 1-Note.docx
Chapter 1-Note.docxChapter 1-Note.docx
Chapter 1-Note.docx
 
Ui 5
Ui   5Ui   5
Ui 5
 
B041130610
B041130610B041130610
B041130610
 
Ios
IosIos
Ios
 
mobile application development -unit-3-
mobile application development  -unit-3-mobile application development  -unit-3-
mobile application development -unit-3-
 
iOS app dev Training - Session1
iOS app dev Training - Session1iOS app dev Training - Session1
iOS app dev Training - Session1
 
Android UI Fundamentals part 1
Android UI Fundamentals part 1Android UI Fundamentals part 1
Android UI Fundamentals part 1
 
React native
React nativeReact native
React native
 
Diving deep in compose.pdf
Diving deep in compose.pdfDiving deep in compose.pdf
Diving deep in compose.pdf
 
Android Study Jam 2
Android Study Jam 2Android Study Jam 2
Android Study Jam 2
 
Ap quiz app
Ap quiz appAp quiz app
Ap quiz app
 
Mobile DevTest Dictionary
Mobile DevTest DictionaryMobile DevTest Dictionary
Mobile DevTest Dictionary
 
Technology and Android.pptx
Technology and Android.pptxTechnology and Android.pptx
Technology and Android.pptx
 
hema ppt (2).pptx
hema ppt (2).pptxhema ppt (2).pptx
hema ppt (2).pptx
 
ios basics
ios basicsios basics
ios basics
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5e
 
Eo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5eEo gaddis java_chapter_14_5e
Eo gaddis java_chapter_14_5e
 
What Is BuildContext In Flutter And It's Importance
What Is BuildContext In Flutter And It's ImportanceWhat Is BuildContext In Flutter And It's Importance
What Is BuildContext In Flutter And It's Importance
 
[PBO] Pertemuan 12 - Pemrograman Android
[PBO] Pertemuan 12 - Pemrograman Android[PBO] Pertemuan 12 - Pemrograman Android
[PBO] Pertemuan 12 - Pemrograman Android
 
Graphical User Interface Development with Eqela
Graphical User Interface Development with EqelaGraphical User Interface Development with Eqela
Graphical User Interface Development with Eqela
 

Recently uploaded

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Recently uploaded (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

6. Chapter 5 - Component In React Navite.pptx

  • 1. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Cross-platform application development
  • 2. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Chapter 5: Component In React Navite  Core Component  Navigation
  • 3. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component What are components?  Components are an abstraction layer on top of the underlying native platform. On an iOS device, a React Native component is ultimately rendered as a UIView. On Android, the same component would be rendered as an android.view. As React Native expands to new platforms, the same code should be able to render correctly on more and more devices.
  • 4. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component View Component  Views are the most basic building block of React Native apps. The View is an abstraction layer on top of the target platform's native equivalent • For iOS - UIView • For Android - android.view • For Web - <div>  View is designed to be nested inside other views and can have 0 to many children of any type
  • 5. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component View Component  There are two fairly distinct things we use View for: • First, we use View for layout. A View is commonly used as a container for other components. If we want to arrange a group of components vertically or horizontally, we will likely wrap those components in a View. • Second, we use View for styling our app. If we want to render a simple shape like a circle or rectangle, or if we want to render a border, a line, or a background color, we will likely use a View.
  • 6. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component  Ex:
  • 7. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Text Component  We use the Text component to render text on the screen. Text can be styled with font- specific attributes such as fontSize. It can use nearly all of the same styles as View, such as backgroundColor and width. However, Text has some key differences when it comes to layout.  Text context will automatically wrap around by default when it fills the width of the component Text dimensions  Unlike the View component, Text components have an intrinsic size  Ex: <Text style={{ backgroundColor: 'red', width: 60, height: 60 }}> Hello World </Text>
  • 8. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Text Component Common Text props and styles  color - A string representing the color of the text.  fontFamily - A string with the name of the font family (this font family must already exist on the device).  fontSize - A number value equal to the size of the font in points.  fontStyle - Either 'normal' or 'italic’.  fontWeight - The thickness of each character. One of 'normal', 'bold', '100', '200', '300’, '400', '500', '600', '700', '800', or '900'. If the chosen weight isn’t available on the device, the nearest available weight will be used instead).  textAlign - The text alignment. One of 'left', 'right', 'center', 'justify' (iOS only), 'auto'.
  • 9. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Text Component Common Text props and styles  numberOfLines - The number of lines to allow before truncating the text.  ellipsizeMode - How text should be truncated when it exceeds numberOfLines. One of 'head’, 'middle', 'tail', 'clip' (iOS only).
  • 10. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Touchable Opacity  The TouchableOpacity component is similar to View, but lets us easily respond to tap gestures in a performant way  One minor inconvenience with both TouchableOpacity and TouchableHighlight: these components can only have a single child element, so if we want multiple children, we will need to wrap them in a View
  • 11. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính
  • 12. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Image  Image component to render images on the screen  There are 3 ways to include images in an app: we can bundle an image asset with our code (which will then get stored on the device), we can download an image from a URI or even from data provided in the 'data:' uri scheme. Bundling image assets • To bundle an image asset, we can require the image by name from our project directory just like any other file <Image source={require('./foo.png')} /> Remote image assets • To display an image from a URI, we must pass an object to the source prop of the Image component <Image source={{ uri: 'https://abc.com/images/img.jpg' }} />
  • 13. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Image Use data provided in the 'data:' uri scheme <Image style={styles.logo} source={{ uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQ BwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgY GBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg==', }} />
  • 14. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Image  Common image styles  resizeMode style (or prop – both work) to determine how the image is cropped in the case where the image data’s intrinsic dimensions are different than the dimensions of the Image component • cover: The image scales uniformly to fill the Image component. The image will be cropped by the bounding box of the component if they have different aspect ratios. • contain: The image scales uniformly to fit within the component. The component’s background color will show if they have different aspect ratios. • stretch: The image stretches to fill the component. • repeat: The image repeats itself at its intrinsic dimensions to fill the component (iOS- only). • center: The image maintains its intrinsic dimensions, and is centered within the component.
  • 15. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Activity Indicator  We can render a loading indicator using the ActivityIndicator component.  This component accepts all the same props as View, plus a few more: • animating: A bool indicating whether to show or hide the indicator (defaults to true). • color: The color of the spinner (defaults to gray). • size: One of 'small' or 'large' (defaults to small).
  • 16. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Activity Indicator  Ex: const [loading, setloading] = useState(true); <View> {loading && ( <ActivityIndicator size={'large'} /> )} </View>
  • 17. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Core Component Flat List Component  FlatList components are used for rendering large quantities of scrollable content. Instead of rendering a children prop, the FlatList renders each item in an input data array using the renderItem prop  The renderItem prop is a function which takes an item from the data array and maps it to a React Element  Ex: • https://reactnative.dev/docs/flatlist
  • 18. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Practice
  • 19. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation What is navigation?  One of the primary navigation patterns in a mobile app is a stack-based pattern. In this pattern, only one screen can be seen by the user at any given time. Navigating involves pushing the new screen onto the navigation stack Native navigation (IOS)  In an iOS application, views are used to build the UI and display content to the user. A view controller (or the UIViewController class) is used to control a set of views and allows us to connect our UI with our application data.
  • 20. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation Native navigation (IOS)  A navigation controller (UINavigationController ) simplifies the process of navigating between screens by allowing us to pass in a stack of UIViewControllers. It will take care of including a header navigation bar at the top of our device with a back button that allows us to pop the current view controller off of the current stack
  • 21. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation Native navigation (IOS)
  • 22. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation Native navigation (Android)  In Android, activities are used to create single screens to define our UI. We can use tasks in order to define a stack of activities known as the back stack  The startActivity method can be used to start a new activity  When this happens, the activity is pushed onto the activity stack. In order to return to the previous screen, the physical back button on every Android device can be pressed in order to run the finish method on the activity. This closes the current activity, pops it off the stack and returns the user back to the previous activity.
  • 23. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation Native navigation (Android)
  • 24. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation React Navigation  Install: npm install @react-navigation/native-stack  In both iOS and Android, a back button at the top of the navigation bar is how a user usually navigates back to a previous screen by removing the current screen off the stack.  On Android devices, there is also a physical or soft key back button at the bottom of the device screen that also allows you to go back on any application.
  • 25. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation React Navigation Creating a native stack navigator  createNativeStackNavigator is a function that returns an object containing 2 properties: Screen and Navigator. Both of them are React components used for configuring the navigator. The Navigator should contain Screen elements as its children to define the configuration for routes.  NavigationContainer is a component which manages our navigation tree and contains the navigation state Moving between screens  Navigating to a new screen • navigation.navigate()  Navigate to a route multiple times • navigation.push()
  • 26. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation React Navigation Moving between screens  Going back • navigation.goBack() • Another alternative would be navigation.popToTop(), which goes back to the first screen in the stack.
  • 27. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation React Navigation  Demo
  • 28. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation React Navigation Passing parameters to routes  There are two pieces to this: • Pass params to a route by putting them in an object as a second parameter to the navigation.navigate function: navigation.navigate('RouteName', { /* params go here */ }) • Read the params in your screen component: route.params.
  • 29. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation React Navigation Passing parameters to routes  Passing params to a previous screen • use the navigate method, which acts like goBack if the screen already exists. You can pass the params with navigate to pass the data back • and use property merge: true <Button title="Done" onPress={() => { // Pass and merge params back to home screen navigation.navigate({ name: 'Home', params: { post: postText }, merge: true, }); }} />
  • 30. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation React Navigation Configuring the header bar <Stack.Navigator> <Stack.Screen name="Home“ component={HomeScreen} options={{ title: 'My home', headerStyle: { backgroundColor: '#f4511e', }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold’, }, }} /> </Stack.Navigator>
  • 31. Trường Đại học Xây dựng Hà Nội Bộ môn Khoa học Máy tính Navigation React Navigation Sharing common options across screens <Stack.Navigator screenOptions={{ headerStyle: { backgroundColor: '#f4511e', }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold’, }, }} > <Stack.Screen name="Home" component={HomeScreen} options={{ title: 'My home' }} /> </Stack.Navigator>

Editor's Notes

  1. yarn add react-navigation
  2. import * as React from 'react'; import { Button, View, Text } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; function HomeScreen({ navigation }) {   return (     <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>       <Text>Home Screen</Text>       <Button         title="Go to Details"         onPress={() => navigation.navigate('Details')}       />     </View>   ); } function DetailsScreen({ navigation }) {   return (     <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>       <Text>Details Screen</Text>       <Button         title="Go to Details... again"         onPress={() => navigation.push('Details')}       />       <Button title="Go to Home" onPress={() => navigation.navigate('Home')} />       <Button title="Go back" onPress={() => navigation.goBack()} />       <Button         title="Go back to first screen in stack"         onPress={() => navigation.popToTop()}       />     </View>   ); } const Stack = createNativeStackNavigator(); function App() {   return (     <NavigationContainer>       <Stack.Navigator initialRouteName="Home">         <Stack.Screen name="Home" component={HomeScreen} />         <Stack.Screen name="Details" component={DetailsScreen} />       </Stack.Navigator>     </NavigationContainer>   ); } export default App;
  3. import * as React from 'react'; import { Text, View, Button, TextInput } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; function HomeScreen({ navigation }) {   const [number, onChangeNumber] = React.useState(null);   return (     <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>       <Text>Home Screen</Text>       <TextInput         style={{height: 100, borderWidth: 1}}         onChangeText={onChangeNumber}         value={number}         placeholder="number"         keyboardType="numeric"       />       <Button         title="Go to Details"         onPress={() => {           /* 1. Navigate to the Details route with params */           navigation.navigate('Details', {             itemId: +number,             otherParam: 'anything you want here',           });         }}       />     </View>   ); } function DetailsScreen({ route, navigation }) {   /* 2. Get the param */   const { itemId } = route.params;   const { otherParam } = route.params;   return (     <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>       <Text>Details Screen</Text>       <Text>itemId: {JSON.stringify(itemId)}</Text>       <Text>otherParam: {JSON.stringify(otherParam)}</Text>       <Button         title="Go to Details... again"         onPress={() =>           navigation.push('Details', {             itemId: Math.floor(Math.random() * 100),           })         }       />       <Button title="Go to Home" onPress={() => navigation.navigate('Home')} />       <Button title="Go back" onPress={() => navigation.goBack()} />     </View>   ); } const Stack = createNativeStackNavigator(); export default function App() {   return (     <NavigationContainer>       <Stack.Navigator>         <Stack.Screen name="Home" component={HomeScreen} />         <Stack.Screen name="Details" component={DetailsScreen} />       </Stack.Navigator>     </NavigationContainer>   ); }
  4. import * as React from 'react'; import { Text, TextInput, View, Button } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; function HomeScreen({ navigation, route }) {   React.useEffect(() => {     if (route.params?.post) {       // Post updated, do something with `route.params.post`       // For example, send the post to the server     }   }, [route.params?.post]);   return (     <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>       <Button         title="Create post"         onPress={() => navigation.navigate('CreatePost')}       />       <Text style={{ margin: 10 }}>Post: {route.params?.post}</Text>     </View>   ); } function CreatePostScreen({ navigation, route }) {   const [postText, setPostText] = React.useState('');   return (     <>       <TextInput         multiline         placeholder="What's on your mind?"         style={{ height: 200, padding: 10, backgroundColor: 'white' }}         value={postText}         onChangeText={setPostText}       />       <Button         title="Done"         onPress={() => {           // Pass and merge params back to home screen           navigation.navigate({             name: 'Home',             params: { post: postText },             merge: true,           });         }}       />     </>   ); } const Stack = createNativeStackNavigator(); export default function App() {   return (     <NavigationContainer>       <Stack.Navigator mode="modal">         <Stack.Screen name="Home" component={HomeScreen} />         <Stack.Screen name="CreatePost" component={CreatePostScreen} />       </Stack.Navigator>     </NavigationContainer>   ); }