React Native Components and JavaScript Lecture PDF

Document Details

ModestBasilisk1424

Uploaded by ModestBasilisk1424

Imam Muhammad ibn Saud Islamic University

Tags

React Native JavaScript components programming

Summary

This PDF lecture covers key concepts in React Native including components, state, props, events and the Fetch API for networking. It also touches on crucial aspects of app security and best practices when dealing with sensitive information such as API keys and user data. Topics range from basic JavaScript features to advanced concepts, suitable for students learning mobile app development.

Full Transcript

Lecture 2: Introduction to Components and JavaScript https://www.reactnative.express/ Overview for today component let and const State and Props Creating a component Events Imports and Exports We use the keyword import to load values from other JavaScript files via rel...

Lecture 2: Introduction to Components and JavaScript https://www.reactnative.express/ Overview for today component let and const State and Props Creating a component Events Imports and Exports We use the keyword import to load values from other JavaScript files via relative path. We use export to expose values for importing. let and const We declare variables with let and constants with const. Avoid variable declarations with var unless maintaining legacy code How do I make my app respond to changes? (e.g. a button click, network request fetch, etc) Component API State and Props Component API State and Props Prop The properties passed to the constructor of a component are called props. > Component API Props Component API Props render() { return ( < souImagerce={{uri: "https://facebook.github.io/react- native/docs/assets/favicon.png"}} /> ); } Parents can pass props down to children. Not the other way around. Component API Props constructor(props) { super(props); //nothing has been rendered yet //-- you can change what is rendered based on these parameters console.log(`constructor ${JSON.stringify(props)}`); } Component API Props Component API State and Props Props The properties passed to the constructor of a component are called props. State An object with details about how a Component should render. Component API State and Props Props The properties passed to the constructor of a component are called props. State An object with details about how a Component should render. This literally is an object named state Props Any JSX attributes become props (parameters) of the React element. The value of an attribute can be any JavaScript expression when wrapped in curly braces, as in bar={baz} (which would set the value of the bar prop to baz). Children Any children elements should go between the opening tag, , and closing tag. Components What are components? React components are the reusable building blocks we use to create the user interface of our app. Components are the type of the React element. We've already seen a few built-in components in lecture 1: View, Text,... We can also define custom components. Defining components There are 2 ways we can define a React component: 1-Function components - A function that takes 2-Class components - A class that parameters (called props) as input, and extends React.Component and implements returns a React element a render method Function Components A function component is a function that returns a React element Composing components We can use custom components like MyComponent in the same way as built-in ones like View. We use props to communicate between components Class Components We can also create components by subclassing React.Component and overriding the render() method. Props are accessible as this.props Class Components import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class App extends React.Component { render() { return ( Hello World! ); } } import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class App extends React.Component { state = { headline: 'Welcome to my app!' } render() { return ( Hello World! ); } } import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class App extends React.Component { state = { headline: 'Welcome to my app!’,.... } render() { return ( {this.state.headline} ); } } Events Some components trigger events/callbacks in response to user input. To add an event handler, pass a function as a prop to a React element Events Introduction to Networking and Security Networking Many mobile apps need to load resources from a remote URL. You may want to make a POST request to a REST API, or you may need to fetch a chunk of static content Using Fetch from another server. Using Fetch React Native provides the Fetch API for your networking needs. Fetch will seem familiar if you have used XMLHttpRequest or other networking APIs before. Making requests In order to fetch content from an arbitrary URL, you can pass the URL to fetch: fetch('https://mywebsite.com/mydata.json’); Making requests Fetch also takes an optional second argument that allows you to customize the HTTP request. You may want to specify additional headers, or make a POST request: fetch('https://mywebsite.com/endpoint/', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ firstParam: 'yourValue', secondParam: 'yourOtherValue', }), }); Using the Fetch API The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network. Unlike XMLHttpRequest that is a callback-based API, Fetch is promise- based and provides a better alternative that can be easily used in service workers. Fetch also integrates advanced HTTP concepts such as CORS and other extensions to HTTP. Basic fetch request async function logMovies() { const response = await fetch("http://example.com/movies.json"); const movies = await response.json(); console.log(movies); } Basic fetch request In the previous slide, we are fetching a JSON file across the network, parsing it, and printing the data to the console. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and does not directly return the JSON response body but instead returns a promise that resolves with a Response object The Response object The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON. Making a request Handling the response In many cases, you will want to do something with the response. Networking is an inherently asynchronous operation. Fetch method will return a Promise that makes it straightforward to write code that works in an asynchronous manner Handling the response const getMoviesFromApi = () => { return fetch('https://reactnative.dev/movies.json').then(response => response.json()).then(json => { return json.movies; }).catch(error => { console.error(error); }); }; Handling the response You can also use the async / await syntax in a React Native app Don't forget to catch any errors that may be thrown by fetch, otherwise they will be dropped silently. const getMoviesFromApiAsync = async () => { try { const response = await fetch( 'https://reactnative.dev/movies.json', ); const json = await response.json(); return json.movies; } catch (error) { console.error(error); } }; Fetch Example import React, {useEffect, useState} from 'react’; // for managing state import {ActivityIndicator, FlatList, Text, View} from 'react-native’; // to display our objects for our data const App = () => { const [isLoading, setLoading] = useState(true); // initially set to true const [data, setData] = useState([]); // in this way is gonna be an empty array const getMovies = async () => { try { const response = await fetch('https://reactnative.dev/movies.json'); const json = await response.json(); //put the response in Jason format setData(json.movies); // we gonna set our data with json.moviw(movie inside Jason file in the website) } catch (error) { // catch the error console.error(error); } finally { setLoading(false); // if the loading is false we can display our flat list } }; useEffect(() => { // to use use effect that hook that we import getMovies(); }, []); return ( {isLoading ? ( // if it is true we gonna show this indicator ):( id} renderItem={({item}) => ( {item.title}, {item.releaseYear} // pass in text )} /> )} ); }; export default App; Security you will learn about some practices for storing sensitive information, authentication, network security, and tools that will help you secure your app. Storing Sensitive Info Never store sensitive API keys in your app code. Anything included in your code could be accessed in plain text by anyone inspecting the app bundle. Tools like react-native-dotenv and react-native-config are great for adding environment-specific variables like API endpoints, but they should not be confused with server-side environment variables, which can often contain secrets and API keys If you must have an API key or a secret to access some resource from your app, the most secure way to handle this would be to build an orchestration layer between your app and the resource. This could be a serverless function (e.g. using AWS Lambda or Google Cloud Functions) which can forward the request with the required API key or secret. Secrets in server side code cannot be accessed by the API consumers the same way secrets in your app code can. Storing Sensitive Info For persisted user data, choose the right type of storage based on its sensitivity. As your app is used, you’ll often find the need to save data on the device, whether to support your app being used offline, cut down on network requests or save your user’s access token between sessions so they wouldn’t have to re-authenticate each time they use the app. Persisted vs unpersisted — persisted data is written to the device’s disk, which lets the data be read by your app across application launches without having to do another network request to fetch it or asking the user to re-enter it. But this also can make that data more vulnerable to being accessed by attackers. Unpersisted data is never written to disk—so there's no data to access! Async Storage Async Storage is a community-maintained module for React Native that provides an asynchronous, unencrypted, key-value store. Async Storage is not shared between apps: every app has its own sandbox environment and has no access to data from other apps Async Storage Secure Storage React Native does not come bundled with any way of storing sensitive data. However, there are pre-existing solutions for Android and iOS platforms. iOS - Keychain Services Keychain Services allows you to securely store small chunks of sensitive info for the user. This is an ideal place to store certificates, tokens, passwords, and any other sensitive information that doesn’t belong in Async Storage. Android - Secure Shared Preferences Shared Preferences is the Android equivalent for a persistent key-value data store. Data in Shared Preferences is not encrypted by default, but Encrypted Shared Preferences wraps the Shared Preferences class for Android, and automatically encrypts keys and values. Android - Keystore The Android Keystore system lets you store cryptographic keys in a container to make it more difficult to extract from the device. Lecture 3A: Lists and TextInputs Overview for today ○ Introducing Hooks ○ Introduce ScrollView. ○ Introduce FlatList and SectionList with networking. ○ Introduce TextInputs. useState useState is the first “Hook” we’ll learn about Output useEffect useEffect is the Second“Hook” we’ll learn about useEffect is a React Hook that lets you synchronize a component with an external system. useEffect(setup, dependencies?) Call useEffect at the top level of your component to declare an Effect setup: The function with your Effect’s logic. optional dependencies: The list of all reactive values referenced inside of the setup code ScrollView and Lists Create an application that has a list with: Customized items Sticky headers Infinite Scrolling Pull down to refresh Fetches info from a server Handles Concurrent Calls ScrollView ScrollView is a react native component library, It allows us to implement scrolling of components with multi-child options, With the help of react native ScrollView library we can scroll vertically and horizontally both which gives user an awesome feeling while surfing on the apps, We need to mention in which direction it should scroll if we do not mention the direction it will scroll in vertical To scroll horizontal we need to mention horizontal: true. ScrollView Attributes Examples showsHorizontalScrollIndicator: It will show an indicator basically for horizontal scrolling when it values are set to true. scrollEnabled: In case if we do not want to scroll our content we can set this property as false. Its value will be true if we do not define any. horizontal: In case if we want to have horizontal scrolling we can set this attribute as true(horizontal=true) Overview for today Live demo ○ Introduce ScrollView. ○ Introduce FlatList and SectionList with networking. ○ Introduce TextInputs. FlatList React native flatlist is like a listview which is used to hold items in a list and provide important features like scrolling horizontally and vertically. Flatlist in reacts native is designed to handle large datasets that might not fit on the device screen. This flatlist performs rendering of only current displaying items on a screen and not all items Basic syntax Basic syntax We can see that the flatlist can be rendered using two primary props that are data and renderItem. Other props like Separator, Header, Footer, and Pulltoscroll are optional components. RefreshControl React Native provides an individual RefreshControl component specifically to implement pull-to-refresh easily in a React Native app. If you’re rendering a list of data using the ScrollView or FlatList component, you can use RefreshControl to add the pull-to-refresh capability. RefreshControl When you initiate the pull-to-refresh gesture, RefreshControl triggers an onRefresh event. The event will execute the code to fetch new data from the server and add it to the screen. While using RefreshControl, you’ll need to handle the state of the component. The refreshing prop indicates whether the refresh is active or not. It should be set to true when you start fetching data and false once the data has been updated. TextInput A foundational component for inputting text into the app via a keyboard. Props provide configurability for several features, such as auto-correction, auto- capitalization TextInput Lecture: Firebase Database Local Data Over network data Fetches have to be tailored to Performance and size are usually what is needed, since it is fetched not an issue over the internet Delivery depends on the user’s Delivery is guaranteed network Typically accessed by 1 session Accessed by an unknown number of the app at a time of sessions of the app at a time Doesn’t worry about concurrency Concurrency is at the heart of it As a Stanford student... Response Request As a Stanford student... Response Request ? ? As a Stanford student... Response Request What is Firebase? It’s a Backend-as-a-Service (aka BaaS) What is Firebase? It’s a Backend-as-a-Service (aka BaaS) Response Request What is Firebase? It’s a Backend-as-a-Service (aka BaaS) I’ll take care of everything Response Request What is Firebase? It’s a Backend-as-a-Service (aka BaaS) Eeeverything? I’ll take care of everything Response Request Yuuuup Firebase Realtime Database Firebase Realtime Database Real time syncing for JSON data. The Firebase Realtime Database is a cloud- hosted NoSQL database that lets you store and sync data between your users in realtime. Firebase Realtime Database Real time syncing for JSON data. The Firebase Realtime Database is a cloud- hosted NoSQL database that lets you store and sync data between your users in realtime. Request To update DB Firebase Realtime Database Real time syncing for JSON data. The Firebase Realtime Database is a cloud- hosted NoSQL database that lets you store and sync data between your users in realtime. Updated Request To update DB Firebase Realtime Database Real time syncing for JSON data. The Firebase Realtime Database is a cloud- hosted NoSQL database that lets you store and sync data between your users in realtime. Updated I have an I have an update update Request To update DB Let’s see how it works! https://docs.expo.io/versions/latest/guides/using-firebase.html https://firebase.google.com/docs/database/ Firebase Realtime Database Store and sync data with our NoSQL cloud database. Data is synced across all clients in realtime, and remains available when your app goes offline. The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our Apple platforms, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data. Use Firebase First , you have created a new Firebase project or have an existing one To creat, follow the instructions in this link https://console.firebase.google.com/u/0/ Initialize the SDK in your project To initialize the Firebase instance in your Expo project, you must create a config object and pass it to the initializeApp() method imported from the firebase/app module. Example: Copy this part of the code from firebase/app module and past it in initializeApp() method in the config filein your project Example: To initialize the Firebase instance in your Expo project Copy this part of the code from firebase/app module and past it in initializeApp() method in the config file in your project Create Realtime Database References Reference your JSON data, such as "users/user:1234/phone_number" to set data or subscribe to data changes. Reference In your in the config file in your project create a reference Example: export const Db = getDatabase(app) ref (alias) ref(Db : Database, path?: string | undefined): DatabaseReference import ref Returns a Reference representing the location in the Database corresponding to the provided path. If no path is provided, the Reference will point to the root of the Database. @param Db — The database instance to obtain a reference for. @param path Optional path representing the location the returned Reference will point. ref If not provided, the returned Reference will point to the root of the Database. @returns If a path is provided, a Reference pointing to the provided path. Otherwise, a Reference pointing to the root of the Database Set Data and Listen for Changes Use (Database References)to write data or subscribe to changes. set set(ref: DatabaseReference, value: unknown): Promise import set Writes data to this Database location. This will overwrite any data at this location and all child locations. The effect of the write will be visible immediately, and the corresponding events ("value", "child_added", etc.) will be triggered. Synchronization of the data to the Firebase servers will also be started, and the returned Promise will resolve when complete. EX: set(ref(Db, id) remove (alias) remove(ref: DatabaseReference): Promise import remove Removes the data at this Database location. Any data at child locations will also be deleted. The effect of the remove will be visible immediately and the corresponding event 'value' will be triggered. Synchronization of the remove to the Firebase servers will also be started, and the returned Promise will resolve when complete. Ex: remove(ref(Db, id)) update (alias) update(ref: DatabaseReference, values: object): Promise import update Writes multiple values to the Database at once. The values argument contains multiple property-value pairs that will be written to the Database together. Each child property can either be a simple property (for example, "name") or a relative path (for example, "name/first") from the current location to the data to update. update As opposed to the set() method, update() can be use to selectively update only the referenced properties at the current location (instead of replacing all the child properties at the current location). The effect of the write will be visible immediately, and the corresponding events ('value', 'child_added', etc.) will be triggered. Ex: update(ref(Db, id) onValue (alias) function onValue(query: Query, callback: (snapshot: DataSnapshot) => unknown, cancelCallback?: ((error: Error) => unknown) | undefined): Unsubscribe (+2 overloads) import onValue Listens for data changes at a particular location. onValue This is the primary way to read data from a Database. Your callback will be triggered for the initial data and again whenever the data changes. Invoke the returned unsubscribe callback to stop receiving updates. See Retrieve Data on the Web for more details. An onValue event will trigger once with the initial data stored at this location, and then trigger again each time the data changes. The DataSnapshot passed to the callback will be for the location at which on() was called. It won't trigger until the entire contents has been synchronized. If the location has no data, it will be triggered with an empty DataSnapshot (val() will return null). CS477 Lecture 4: Introduction to Navigation Single Screen App What happens when you want to show a different screen? Maybe a Settings screen, or an individual screen for one of those articles? Single Screen App School of thought React Native navigation should be based off “native” iOS and Android navigation components. Usually a Java and Swift/Obj-C implementation School of thought React Native navigation should be based off Native Navigation “native” iOS and Android navigation React Native Navigation http://airbnb.io/native-navigation/ https://github.com/wix/react-native- components. navigation Usually a Java and Swift/Obj-C implementation School of thought React Native navigation should be based off as many existing components in the JavaScript layer. A JavaScript Implementation React Navigation https://reactnavigation.org React Navigation https://reactnavigation.org JavaScript implementation means: Greatest amount of customization Better fit for the RN ecosystem Room for growth independent of the navigation solutions that native platforms provide Integration with existing state-management systems like Redux (we’ll cover Redux later in the quarter) React Navigation https://reactnavigation.org Stack Tab Drawer Navigator Navigator Navigator Stack Tab Drawer Navigator Navigator Navigator Stack Tab Drawer Navigator Navigator Navigator Stack Tab Drawer Navigator Navigator Navigator Stack Tab Drawer Navigator Navigator Navigator Stack Tab Drawer Navigator Navigator Navigator Stack Tab Drawer Navigator Navigator Navigator Stack Tab Drawer Navigator Navigator Navigator Stack Tab Drawer Navigator Navigator Navigator Using AsyncStorage Pushing Data - AsyncStorage.setItem(key, val) Fetching Data - AsyncStorage.getItem(key) Removing Data - AsyncStorage.removeItem(key) Clearing - AsyncStorage.clear() All keys - AsyncStorage.getAllKeys() Multi pushing - AsyncStorage.multiSet(array) Multi getting - AsyncStorage.multiGet(array) Stack Tab Drawer Navigator Navigator Navigator + Q&A (prepare questions Guest Lecture for CS47SI & bring laptops) Tuesday, February 6th, 2018 Yixin Wan Internal Uses Christopher Chedeau History & Development Alexander Kotliarskyi Building Scalable Apps Wrapping your app in NavigationContainer Now, we need to wrap the whole app in NavigationContainer. Usually you'd do this in your entry file, such as App.js: Wrapping your app in NavigationContainer import * as React from 'react'; import { NavigationContainer } from '@react-navigation/native'; export default function App() { return ( {} ); } Wrapping your app in NavigationContainer In a typical React Native app, the NavigationContainer should be only used once in your app at the root. You shouldn't nest multiple NavigationContainers unless you have a specific use case for them. NavigationContainer is a component which manages our navigation tree and contains the navigation state. This component must wrap all navigators structure. Usually, we'd render this component at the root of our app, which is usually the component exported from App.js. 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. Example 1 Example 1:run q You can see a screen with an empty navigation bar and a grey content area containing your HomeScreen component. q The styles you see for the navigation bar and the content area are the default configuration for a stack navigator Configuring the navigator All of the route configuration is specified as props to our navigator. In the example 1, we haven't passed any props to our navigator, so it just uses the default configuration Example 2 Let's add a second screen to our native stack navigator in Example 1 and configure the Home screen to render first Example 2 Example 2 Now our stack has two routes, a Home route and a Details route. A route can be specified by using the Screen component. The Screen component accepts a name prop which corresponds to the name of the route we will use to navigate A component prop which corresponds to the component it'll render. Example 2 The Home route corresponds to the HomeScreen component The Details route corresponds to the DetailsScreen component. The initial route for the stack is the Home route. Try changing it to Details and reload the app (React Native's Fast Refresh won't update changes from initialRouteName, as you might expect), notice that you will now see the Details screen. Then change it back to Home and reload once more Example 2 Note: The component prop accepts component, not a render function. Don't pass an inline function (e.g. component={() => }), Specifying options Each screen in the navigator can specify some options for the navigator, such as the title to render in the header. These options can be passed in the options prop for each screen component. Moving between screens We will learn how to let a user navigate from Home to Details. If this was a web browser, we'd be able to write something like this: Go to Details Another way to write this would be: { window.location.href = 'details.html'; }} > Go to Details We'll do something similar to the latter, but rather than using a window.location global, we'll use the navigation prop that is passed down to our screen components. Navigating to a new screen: Example Navigating to a new screen: Example navigation - the navigation prop is passed in to every screen component (definition) in the native stack navigator. navigate('Details') - we call the navigate function (on the navigation prop — naming is hard!) with the name of the route that we'd like to move the user to. Navigating to a new screen Navigate to a route multiple times What would happen if we navigated to the Details route again, from the Details screen? Navigate to a route multiple times Navigate to a route multiple times If you run this code, you'll notice that when you tap "Go to Details... again" that it doesn't do anything! This is because we are already on the Details route. The navigate function roughly means "go to this screen", and if you are already on that screen then it makes sense that it would do nothing Navigate to a route multiple times We can change navigate to push. This allows us to express the intent to add another route regardless of the existing navigation history. Each time you call push we add a new route to the navigation stack. When you call navigate it first tries to find an existing route with that name, and only pushes a new route if there isn't yet one on the stack. Going back Summary React Native doesn't have a built-in API for navigation like a web browser does. React Navigation provides this for you, along with the iOS and Android gestures and animations to transition between screens. Stack.Navigator is a component that takes route configuration as its children with additional props for configuration and renders our content. Each Stack.Screen component takes a name prop which refers to the name of the route and component prop which specifies the component to render for the route. These are the 2 required props. To specify what the initial route in a stack is, provide an initialRouteName as the prop for the navigator. To specify screen-specific options, we can pass an options prop to Stack.Screen, and for common options, we can pass screenOptions to Stack.Navigator Summary navigation.navigate('RouteName') pushes a new route to the native stack navigator if it's not already in the stack, otherwise it jumps to that screen. We can call navigation.push('RouteName') as many times as we like and it will continue pushing routes. The header bar will automatically show a back button, but you can programmatically go back by calling navigation.goBack(). On Android, the hardware back button just works as expected. You can go back to an existing screen in the stack with navigation.navigate('RouteName'), and you can go back to the first screen in the stack with navigation.popToTop(). The navigation prop is available to all screen components (components defined as screens in route configuration and rendered by React Navigation as a route). Lecture 1: Basic React Native Components + Stylesheets Vanilla React Native uses Babel as a preprocessor ES6 + JSX ECMAScript 6 Extension Vanilla React Native uses Babel as a preprocessor ES6 + JSX ECMAScript 6 Extension ES6 (ECMAScript 6) Cleaner (fat arrow) functions. var _this = this; var foo = function foo() { return 'bar'; const foo = () => 'bar' }; const baz = (x) => { var baz = function baz(x) { return x + 1 return x + 1; } }; this.items.map(x => this.doSomethingWith(x)) this.items.map(function (x) { return _this.doSomethingWith(x); }); Vanilla React Native uses Babel as a preprocessor ES6 + JSX ECMAScript 6 Extension let textLayer = CATextLayer()... self.view.layer.addSublayer(textLayer) const ourNestedView = ( 42 ) const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, }); Basically “CSS” brought to a mobile platform https://github.com/vhpoet/react-native-styling-cheat-sheet Overview for today Introduce core React Native components. Layouts and flexboxes. Experiment with common layouts, and how to achieve them. Components Different classes that inherit from the React Component class Components Different classes that inherit from the React Component class Importance: renderable! Components Different classes that inherit from the React Component class Importance: renderable! Common Components: - View - Text - Image - Lists - Scrollviews - Touchables Components Different classes that inherit from the React Component class Importance: renderable! Common Components: - View - Text - Image - Lists - Scrollviews - Touchables Component Your component starts as a function: const Cat = () => {}; You can think of components as blueprints. Whatever a function component returns is rendered as a React element. React elements let you describe what you want to see on the screen. Here the Cat component will render a element: const Cat = () => { return Hello, I am your cat!; }; EX: View Most common visual styles backgroundColor: “red” borderWidth: 2 borderColor: “green” borderRadius: 10 opacity: 0.3 Common uses: wrapper around images, background, layout control View Using the different styles we can get pretty interesting shapes Text Not the most interesting component, but still useful... color: “red” fontWeight: “bold” fontSize: 16 fontFamily: “Helvatica” backgroundColor: “black” Text Text allows nesting I am bold and red Text Has an onPress and onLongPress handlers console.log(“bold clicked”) style={{fontWeight: 'bold'}}> I am bold and red Image Surprise! Used to display images Uses URI or Assets to display the photos Image Surprise! Used to display images Uses URI or Assets to display the photos Image You can specify the resize mode of the image - - - - Components Different classes that inherit from the React Component class Importance: renderable! Common Components: - View - Text - Image - Lists - Scrollviews - Touchables Absolute Positioning you can also utilize absolute positioning to place elements on the screen. The precise coordinates of an element within its parent container can be specified by using absolute positioning. The distance between the element and each of the container’s boundaries can then be specified using the top, left, right, and bottom style parameters. Coordinates Container: { position: ‘absolute’, start: 0, top: 0, width: 50, height: 50... } Coordinates Coordinates Relative, percentages Container: { start: ‘10%’, top: ‘10%’, width: ‘5%’, height: ‘5%’... } Relative, percentages Relative, percentages Relative, percentages Appropriate margins? Screen ratio change? Safe area around? Flexboxes Container: { justifyContent: ‘space-around’, alignItems: ‘center’,... } Flexboxes Flexboxes Flexboxes Property Default Options flexDirection column row, column justifyContent flex-start flex-start, center, flex-end, space-around, space-between alignItems stretch flex-start, center, flex-end, stretch http://www.reactnativeexpress.com/flexbox From design to code ➔ Break down the design. ➔ Choose components for each part. ➔ Code out the components tree and style it. Example 1 Output N AV I G AT I O N : PA R T 2 Tab navigation Drawer navigation Tab navigation Possibly the most common style of navigation in mobile apps is tab-based navigation. This can be tabs on the bottom of the screen or on the top below the header (or even instead of a header). Example Example Customizing the appearance This is similar to how you would customize a stack navigator — there are some properties that are set when you initialize the tab navigator and others that can be customized per- screen in options. Customizing the appearance Customizing the appearance: Customizing the appearance Add badges to icons Sometimes we want to add badges to some icons. You can use the tabBarBadge option to do it: Jumping between tabs A stack navigator for each tab Usually tabs don't just display one screen — for example, on your Twitter feed, you can tap on a tweet and it brings you to a new screen within that tab with all of the replies. You can think of this as there being separate navigation stacks within each tab, and that's exactly how we will model it in React Navigation. A stack navigator for each tab A stack navigator for each tab Drawer navigation Common pattern in navigation is to use drawer from left (sometimes right) side for navigating between screens. Example of drawer-based navigation Opening and closing drawer To open and close drawer, use the following helpers: navigation.openDrawer(); navigation.closeDrawer(); Drawer Navigator Drawer Navigator renders a navigation drawer on the side of the screen which can be opened and closed via gestures. Example Props The Drawer.Navigator component accepts following props: id Optional unique ID for the navigator. This can be used with navigation.getParent to refer to this navigator in a child navigator. initialRouteName The name of the route to render on the first load of the navigator. screenOptions Default options to use for the screens in the navigator. Props backBehavior This controls what happens when goBack is called in the navigator. This includes pressing the device's back button or back gesture on Android. It supports the following values: firstRoute - return to the first screen defined in the navigator (default) initialRoute - return to initial screen passed in initialRouteName prop, if not passed, defaults to the first screen order - return to screen defined before the focused screen history - return to last visited screen in the navigator; if the same screen is visited multiple times, the older entries are dropped from the history none - do not handle back button defaultStatus The default status of the drawer - whether the drawer should stay open or closed by default. When this is set to open, the drawer will be open from the initial render. It can be closed normally using gestures or programmatically. However, when going back, the drawer will re- open if it was closed. This is essentially the opposite of the default behavior of the drawer where it starts closed, and the back button closes an open drawer drawerContent Function that returns React element to render as the content of the drawer, for example, navigation items The content component receives the following props by default: state - The navigation state of the navigator. navigation - The navigation object for the navigator. descriptors - An descriptor object containing options for the drawer screens. The options can be accessed at descriptors[route.key].options. Providing a custom drawerContent The default component for the drawer is scrollable and only contains links for the routes in the RouteConfig. You can easily override the default component to add a header, footer, or other content to the drawer. Providing a custom drawerContent you can use DrawerContentScrollView to handle this automatically: Providing a custom drawerContent To add additional items in the drawer, you can use the DrawerItem component: DrawerItem component The DrawerItem component accepts the following props: label (required): The label text of the item. Can be string, or a function returning a react element icon: Icon to display for the item. Accepts a function returning a react element. e.g. ({ focused, color, size }) =>. focused: Boolean indicating whether to highlight the drawer item as active. onPress (required): Function to execute on press. DrawerItem component: Cont.. activeTintColor: Color for the icon and label when the item is active. inactiveTintColor: Color for the icon and label when the item is inactive. activeBackgroundColor: Background color for item when it's active. inactiveBackgroundColor: Background color for item when it's inactive. labelStyle: Style object for the label Text. style: Style object for the wrapper View. custom component To use the custom component, we need to pass it in the drawerContent prop: Example: Options The following options can be used to configure the screens in the navigator. These can be specified under screenOptions prop of Drawer.navigator or options prop of Drawer.Screen. title A generic title that can be used as a fallback for headerTitle and drawerLabel. lazy Whether this screen should render the first time it's accessed. Defaults to true. Set it to false if you want to render the screen on initial render. drawerLabel String or a function that given { focused: boolean, color: string } returns a React.Node, to display in drawer sidebar. When undefined, scene title is used. Options drawerIcon Function, that given { focused: boolean, color: string, size: number } returns a React.Node to display in drawer sidebar. drawerActiveTintColor Color for the icon and label in the active item in the drawer. drawerActiveBackgroundColor Background color for the active item in the drawer. Options drawerInactiveTintColor Color for the icon and label in the inactive items in the drawer. drawerInactiveBackgroundColor Background color for the inactive items in the drawer. drawerItemStyle Style object for the single item, which can contain an icon and/or a label. drawerLabelStyle Style object to apply to the Text style inside content section which renders a label. Options drawerContentContainerStyle Style object for the content section inside the ScrollView. drawerContentStyle Style object for the wrapper view. drawerStyle Style object for the drawer component. You can pass a custom background color for a drawer or a custom width here. Options: Example Example Navigation Nesting navigators Nesting navigators Nesting navigators means rendering a navigator inside a screen of another navigator for example: Nesting navigators In the previous example, the Home component contains a tab navigator. The Home component is also used for the Home screen in your stack navigator inside the App component. So here, a tab navigator is nested inside a stack navigator: Stack.Navigator Home (Tab.Navigator) Feed (Screen) Messages (Screen) Profile (Screen) Settings (Screen) Nesting navigators work very much like nesting regular components. To achieve the behavior you want, it's often necessary to nest multiple navigators. How nesting navigators affects the behavior Each navigator keeps its own navigation history Each navigator has its own options For example, specifying a title option in a screen nested in a child navigator won't affect the title shown in a parent navigator. Each screen in a navigator has its own params For example, any params passed to a screen in a nested navigator are in the route prop of that screen and aren't accessible from a screen in a parent or child navigator. How nesting navigators affects the behavior Navigation actions are handled by current navigator and bubble up if couldn't be handled In the previous example, when calling navigate('Messages'), inside Feed screen, the nested tab navigator will handle it, but if you call navigate('Settings'), the parent stack navigator will handle it. Navigator specific methods are available in the navigators nested inside For example, if you have a stack inside a drawer navigator, the drawer's openDrawer, closeDrawer, toggleDrawer methods etc. will also be available on the navigation prop in the screen's inside the stack navigator. But say you have a stack navigator as the parent of the drawer, then the screens inside the stack navigator won't have access to these methods, because they aren't nested inside the drawer. Receiving events from parent navigator If you have a stack navigator nested inside a tab navigator, the screens in the stack navigator won't receive the events emitted by the parent tab navigator such as (tabPress) when using navigation.addListener. To receive events from parent navigator, you can explicitly listen to parent's events with navigation.getParent: Passing params to a screen in a nested navigator You can also pass params by specifying a params key for Example : Passing params to a screen in a nested navigator Best practices when nesting We recommend to reduce nesting navigators to minimal. Try to achieve the behavior you want with as little nesting as possible. Nesting has many downsides: It results in deeply nested view hierarchy which can cause memory and performance issues in lower end devices Nesting same type of navigators (e.g. tabs inside tabs, drawer inside drawer etc.) might lead to a confusing UX With excessive nesting, code becomes difficult to follow when navigating to nested screens, configuring deep link Best practices when nesting We recommend to reduce nesting navigators to minimal. Try to achieve the behavior you want with as little nesting as possible. Nesting has many downsides: It results in deeply nested view hierarchy which can cause memory and performance issues in lower end devices Nesting same type of navigators (e.g. tabs inside tabs, drawer inside drawer etc.) might lead to a confusing UX With excessive nesting, code becomes difficult to follow when navigating to nested screens, configuring deep link etc Example

Use Quizgecko on...
Browser
Browser