CIS 470 Mobile App Development React Native Lecture
CIS 470 Mobile App Development React Native Lecture #1 Wenbing Zhao Department of Electrical Engineering and Computer Science Cleveland State University 2/15/2022 CIS 470: Mobile App Development 1
React Native n n n Facebook released React Native in 2015 and has been maintaining it ever since Create native apps for Android and i. OS using Javascript Many platforms, one React. Create platform-specific versions of components so a single codebase can share code across platforms. React Native lets you create truly native apps and doesn't compromise your users' experiences. It provides a core set of platform agnostic native components like View, Text, and Image that map directly to the platform’s native UI building blocks. 2/15/2022 Android Sensor Programming 2
Setting up Development Enviornment n n n Download node. js and install it: https: //nodejs. org/en/download/ npm package manager will be installed as part of nodejs I prefer yarn package manager. So, install yarn next q n The standard way of working on react native project is using expo (https: //docs. expo. io) q n npm install -g yarn Install command line tools expo-cli: npm install --global expo-cli To create a project using expo, go to a folder that you want to host the project, then type: q q 2/15/2022 expo init my-project Then: cd my-project Android Sensor Programming 3
Creating a React Native Projecdt n To create a project using expo, go to a folder that you want to host the project, then type: q expo init my-project ? Choose a template: › - Use arrow-keys. Return to submit. ----- Managed workflow ----� blank a minimal app as clean as an empty canvas blank (Type. Script) same as blank but with Type. Script configuration tabs (Type. Script) several example screens and tabs using react-navigation and Type. Script ----- Bare workflow ----minimal bare and minimal, just the essentials to get you started minimal (Type. Script) same as minimal but with Type. Script configuration q Choose the default “blank”, then expo will use ”yarn” to install packages. Once done, you will see: ✔ Installed Java. Script dependencies. �Your project is ready! To run your project, navigate to the directory and run one of the following yarn commands. - cd my-project - yarn start # you can open i. OS, Android, or web from here, or run them directly with the commands below. - yarn android - yarn ios - yarn web 2/15/2022 Android Sensor Programming 4
Getting Started n Starting the development server Make sure you are within in the project folder (cd my-project) q Type: expo start When you run expo start (or npm start), Expo CLI starts Metro Bundler, which is an HTTP server that compiles the Java. Script code of our app using Babel and serves it to the Expo app. It also pops up Expo Dev Tools, a graphical interface for Expo CLI q n 2/15/2022 Android Sensor Programming 5
Getting Started n In the terminal where you started “expo start”, you will see: › Waiting on exp: //10. 0. 1. 27: 19000 › Scan the QR code above with Expo Go (Android) or the Camera app (i. OS) › Press a │ open Android › Press i │ open i. OS simulator › Press w │ open web › Press d │ open developer tools › shift+d │ toggle auto opening developer tools on startup (enabled) › Press e │ share the app link by email › Press ? │ show all commands Logs for your project will appear below. Press Ctrl+C to exit. n You may use the Android emulator you already setup, or experiment with the web emulator 2/15/2022 Android Sensor Programming 6
Making Your First Change n n To write Javascript code for React Native project, you will need an editor The best one is Visual Studio Code q n https: //code. visualstudio. com/Download To make changes to the project, open App. js using Code import { Status. Bar } from 'expo-status-bar'; import React from 'react'; import { Style. Sheet, Text, View } from 'react-native'; export default function App() { return ( <View style={styles. container}> <Text>Open up App. js to start working on your app!</Text> <Status. Bar style="auto" /> </View> ); } change the text to "Hello, world!" const styles = Style. Sheet. create({ container: { flex: 1, background. Color: '#fff’, align. Items: 'center’, justify. Content: 'center’, }, }); 2/15/2022 Android Sensor Programming 7
Adding Style n n Our text is black and small. We'll also increase the font size to make it easier to read #888 is equal parts red, green, and blue import { Status. Bar } from 'expo-status-bar'; import React from 'react'; import { Style. Sheet, Text, View } from 'react-native'; export default function App() { return ( <View style={styles. container}> <Text style={{color: '#888', font. Size: 18}}> Hello World </Text> <Status. Bar style="auto" /> </View> ); } const styles = Style. Sheet. create({ container: { flex: 1, background. Color: '#fff’, align. Items: 'center’, justify. Content: 'center’, }, }); 2/15/2022 Android Sensor Programming 8
Adding an Image n n n We can display the image using the Image component When creating an Image component, you will need to explicitly specify a width and height, or the image won't be visible Download the top image from: https: //docs. expo. io/tutorial/image/ and save it to assets subfoler in your project folder 2/15/2022 Android Sensor Programming 9
Adding an Image n Change the App. js source code: import { Status. Bar } from 'expo-status-bar'; import React from 'react'; import { Image, Style. Sheet, Text, View } from 'react-native'; import logo from '. /assets/logo. png'; export default function App() { return ( <View style={styles. container}> <Image source={logo} style={{ width: 305, height: 159 }} /> <Text style={{color: '#888', font. Size: 18}}> Hello World </Text> <Status. Bar style="auto" /> </View> ); } const styles = Style. Sheet. create({ container: { flex: 1, background. Color: '#fff', align. Items: 'center', justify. Content: 'center', }, }); 2/15/2022 What have been changed: 1. Import Image from ‘react-native’ 2. Import logo from assets 3. Added the <Image> component Android Sensor Programming 10
Adding an Image n We can also add an image that is from the Web by providing a uri to the image <Image source={{ uri: "https: //i. imgur. com/Tk. Ir. Sc. D. png" }} style={{ width: 305, height: 159 }} /> n https: //i. imgur. com/Tk. Ir. Sc. D. png is exactly the logo image 2/15/2022 Android Sensor Programming 11
Adding an Image: Refactor the styles n Move the styles (such as color and size etc. ) to the styles section export default function App() { return ( <View style={styles. container}> <Image source={{ uri: "https: //i. imgur. com/Tk. Ir. Sc. D. png" }} style={styles. logo} /> <Text style={styles. instructions} > To share a photo from your phone with a friend, just press the button below! </Text> </View> ); } const styles = Style. Sheet. create({ container: { flex: 1, background. Color: '#fff’, align. Items: 'center’, justify. Content: 'center’, }, logo: { width: 305, height: 159, margin. Bottom: 10, }, instructions: { color: '#888’, font. Size: 18, margin. Horizontal: 15, }, }); 2/15/2022 Android Sensor Programming 12
Adding a Button n We can create our own custom button using the Touchable. Opacity component and some styled Text inside of it <Touchable. Opacity on. Press={() => alert('Hello, world!’)} style={{ background. Color: 'blue' }}> <Text style={{ font. Size: 20, color: '#fff' }}>Pick a photo</Text> </Touchable. Opacity> export default function App() { return ( <View style={styles. container}> <Image source={{ uri: "https: //i. imgur. com/Tk. Ir. Sc. D. png" }} style={styles. logo} /> <Text style={styles. instructions} > To share a photo from your phone with a friend, just press the button below! </Text> <Touchable. Opacity on. Press={() => alert('Hello, world!')} style={{ background. Color: 'blue' }}> <Text style={{ font. Size: 20, color: '#fff' }}>Pick a photo</Text> </Touchable. Opacity> </View> ); } 2/15/2022 An alert is displayed when you click the button Android Sensor Programming 13
Adding a Button n button: { background. Color: "blue", padding: 20, border. Radius: 5, }, button. Text: { font. Size: 20, color: '#fff’, }, We can make our button bigger by adding some padding to our Touchable. Opacity const styles = Style. Sheet. create({ export default function App() { return ( <View style={styles. container}> <Image source={{ uri: 'https: //i. imgur. com/Tk. Ir. Sc. D. png' }} style={styles. logo} /> <Text style={styles. instructions}> To share a photo from your phone with a friend, just press the button below! </Text> <Touchable. Opacity on. Press={() => alert('Hello, world!')} style={styles. button}> <Text style={styles. button. Text}>Pick a photo</Text> </Touchable. Opacity> </View> ); } 2/15/2022 container: { flex: 1, background. Color: '#fff', align. Items: 'center', justify. Content: 'center', }, logo: { width: 305, height: 159, margin. Bottom: 20, }, instructions: { color: '#888', font. Size: 18, margin. Horizontal: 15, margin. Bottom: 10, }, button: { background. Color: "blue", padding: 20, border. Radius: 5, }, button. Text: { font. Size: 20, color: '#fff', }, }); Android Sensor Programming 14
Javascript n Javascript engines q n Babel q q n Our Java. Script code runs in a Java. Script "engine", or interpreter, on mobile devices. On i. OS, our code runs in JSC, the same open source engine used by the Safari web browser. On Android, our code can either use JSC, or a new engine from Facebook called Hermes Babel is a highly configurable compiler that lets us use newer Java. Script language features (and extensions, like JSX), compiling "down" into older versions of Java. Script that are supported on a wider range of engines When we initialize a new React Native app, a Babel configuration file, babel. config. js, is generated alongside our project Type. Script q q q Java. Script is dynamically typed, which means that type checking happens at runtime. This is convenient for small scripts, but for large apps it's often helpful to have type checking at compile-time. Type. Script extends Java. Script, adding syntax for type declarations and annotations Expo includes a Type. Script template 2/15/2022 Android Sensor Programming 15
Javascript Language Highlights n n n n Imports and exports Block-scoped declarations Arrow functions Classes Destructuring Spread Async/await 2/15/2022 Android Sensor Programming 16
Imports and Exports n n We use the keyword import to load values from other Java. Script files via relative path We use export to expose values for importing my. Number. js index. js export default 42 import my. Number from '. /my. Number' console. log(my. Number) 2/15/2022 Android Sensor Programming 17
Named Imports and Exports n A single file can have multiple exports, and any subset of these can be imported simultaneously my. Values. js index. js export const my. Number = 42 import { my. Number, my. String } from '. /my. Values' export const my. String = 'Hello, world!' console. log(my. Number, my. String) 2/15/2022 Android Sensor Programming 18
Importing from modules n n There's a shorter syntax for importing 3 rd party libraries: we import the name of the module's directory within node_modules Libraries specify a "main" file in their package. json, either index. js (without expo) or App. js (with Expo), which is what actually gets imported q E. g. assuming we had downloaded the moment library into our node_modules, we could import '. /node_modules/moment/index. js' with just 'moment'. Importing a library import moment from 'moment' console. log(moment(). format('MMMM Do YYYY, h: mm: ss a')) Output "April 18 th 2021, 9: 04: 27 pm" 2/15/2022 Android Sensor Programming 19
Block-Scoped Declarations n n let and const: We declare variables with let and constants with const Avoid variable declarations with var unless maintaining legacy code let my. Variable = 42 my. Variable = 43 let my. Undefined. Variable const my. Constant = 42 // Reassigning: compile-time error! // my. Constant = 43 // Avoid! var my. Legacy. Variable = 42 2/15/2022 Android Sensor Programming 20
Block-Scoped Declarations n Constants with mutable values q q With const, a name is permanently bound to a value in scope and can't be reassigned However, if the value is an object, then the value is still mutable const my. Constant = [1, 2, 3] // Reassigning the name: not allowed // my. Constant = [7, 8, 9] // Mutating the value: allowed my. Constant. push(4) console. log(my. Constant) (4) [1, 2, 3, 4] 0: 1 1: 2 2: 3 3: 4 2/15/2022 Android Sensor Programming 21
Arrow Functions n There are two syntaxes for declaring functions: q q n The function keyword Arrow (=>) function expressions The => syntax is a newer, more lightweight syntax for defining functions. However, these syntaxes have somewhat different behavior, so arrow functions are more than just a new syntax q q If the function takes exactly one parameter, the parentheses can be omitted: x => Math. pow(x, 2) Any other number of arguments will need parentheses: (x, y) => Math. pow(x, y) If the function body is not wrapped in curly braces (as in the previous sentences), it is executed as an expression, and the return value of the function is the value of the expression The function body can be wrapped in curly braces to make it a block, in which case you will need to explicitly return a value, if you want something returned 2/15/2022 Android Sensor Programming 22
Arrow Functions n Naming q q Functions defined with => are always anonymous, while functions defined with function can optionally be named Naming can be very helpful in stack traces when debugging A named function foo is defined as function foo(), which simultaneously introduces the variable name foo into scope This is different than const foo = () => {}, which introduces the variable name foo pointing to an anonymous function 2/15/2022 Android Sensor Programming 23
Classes n n Java. Script supports object-oriented programming with classes Java. Script classes support single inheritance, private properties/methods, and static (i. e. class) properties/methods Classes don't support interfaces (i. e. protocols or type classes), so they may feel somewhat limited compared to other languages Many developers prefer programming without classes, instead using functional patterns and storing data in plain Java. Script objects class Cat { constructor(name) { this. name = name } } const my. Cat = new Cat('nyan') console. log(my. Cat) name: "nyan" console. log(`My name is ${my. Cat. name}`) "My name is nyan" console. log(my. Cat instanceof Cat) true 2/15/2022 Android Sensor Programming 24
Destructuring n n We can use destructuring to extract multiple values from an object or array and assign them to variables simultaneously We can extract multiple values within an object const my. Object = { name: 'Devin', age: 29, } const { name, age } = my. Object console. log(name, age) n "Devin” 29 Destructuring arrays const my. Array = [1, 2, 3] const [a, b, c] = my. Array console. log(a, b, c) 2/15/2022 123 Android Sensor Programming 25
Destructuring n Destructuring function arguments const my. Object = { name: 'Devin', age: 29, } function my. Function({ name, age }) { return `${name}: ${age}` } console. log(my. Function(my. Object)) 2/15/2022 "Devin” 29 Android Sensor Programming 26
Destructuring n Advanced destructuring: q q We can also nest and rename destructured variables and supply default values. The rest syntax. . . collects remaining values. Rest is roughly the inverse of spread const people = { name: 'Devin', age: 29, hair. Color: undefined, eye. Color: 'blue', location: { city: 'San Francisco', }, } const { name: my. Name, hair. Color = 'brown', location: { city }, . . . other. Properties } = people console. log(my. Name, hair. Color, city, other. Properties) 2/15/2022 "Devin" "brown" "San Francisco" {age: 29, eye. Color: "blue"} age: 29 eye. Color: "blue" Android Sensor Programming 27
Spread n The spread syntax. . . is a convenient way to merge or copy Objects and Arrays: const my. Array 1 = [3, 4, 5] const my. Array 2 = [1, 2, . . . my. Array 1, 6, 7] console. log(my. Array 2) const my. Object 1 = { name: 'Devin', hair. Color: 'brown' } const my. Object 2 = {. . . my. Object 1, age: 29 } console. log(my. Object 2) 2/15/2022 name: "Devin" hair. Color: "brown" age: 29 Android Sensor Programming 28
Async and Await n n n The keywords async and await are special syntax for working with promises A function marked as async always returns a Promise — if we return a non-promise value, it's automatically wrapped in Promise. resolve Within the function, we can use await to wait for a promise to be resolved or rejected and access its value const fetch. Data = async () => { const response = await fetch('https: //randomuser. me/api/') const data = await response. json() return data } const print. Data = async () => { try { const data = await fetch. Data() console. log('Data', data) } catch (error) { console. error('Problem', error) } } print. Data() 2/15/2022 Android Sensor Programming 29
JSX n n n Why JSX? The XML-like syntax is typically more concise, easier to read, and visually looks a little like the generated UI (both are tree-like) JSX is an extension to the Java. Script language that adds a new kind of expression, the JSX expression, used to create React elements JSX expressions are a concise syntax for calling the API, React. create. Element(type, props, . . . children) Type: q Like XML, each JSX expression has a tag, e. g. <View />, which is then transformed into a call to React. create. Element(View). In this case, View is the type of the element const element = <View /> var element=React. create. Element(View, null); Babel Output n Props: q q Any JSX attributes become props (parameters) of the React element The value of an attribute can be a string, like foo="hello", or it can be any Java. Script expression when wrapped in curly braces, as in bar={baz} (which would set the value of the bar prop to baz) const element = <View foo="hello" bar={baz} /> var element=React. create. Element(View, {foo: "hello", bar: baz}); Babel Output 2/15/2022 Android Sensor Programming 30
JSX n Children: q q Any children elements should go between the opening tag, <View>, and closing tag </View> Elements without children can use a self-closing tag, like <View />, as a shorthand const element = ( <View> <Text /> <Image /> </View> ) n var element= React. create. Element(View, null, React. create. Element(Text, null), React. create. Element(Image, null)); Babel Output Interpolation: q Children are generally other elements, but can also be any other kind of expression if wrapped in curly braces, {. . . } const my. Variable = <Image /> var my. Variable=React. create. Element(Image, null); const element = ( <View> <Text /> {my. Variable} </View> ) var element= React. create. Element(View, null, React. create. Element(Text, null), my. Variable); 2/15/2022 Babel Output Android Sensor Programming 31
- Slides: 31