React Native Guide
React Native Guide
JavaScript Variables
• let num = 5;
var x;
let y;
var is used in the older versions of let is the new way of declaring variables starting
JavaScript ES6 (ES2015).
Variable declared by let cannot be redeclared and must be declared before use
whereas variables declared with var keyword are hoisted.
Variable names must start with either a letter, an underscore _ , or the dollar
sign $ . For example,
1. //valid
2. let a = 'hello';
3. let _a = 'hello';
4. let $a = 'hello';
5. //invalid
6. Let 1a = 'hello'; // this gives an error
7. let y = "hi";
8. let Y = 5;
9.
10. console.log(y); // hi
11. console.log(Y); // 5
12. //invalid
13. let new = 5; // Error! new is a keyword.
Note:
• Though you can name variables in any way you want, it's a good practice to
give a descriptive variable name. If you are using a variable to store the
number of apples, it better to use apples or numberOfApples rather than x or n .
• In JavaScript, the variable names are generally written in camelCase if it has
multiple words. For example, firstName , annualSalary , etc.
JavaScript Constants
The const keyword was also introduced in the ES6(ES2015) version to create
constants. For example,
const x = 5;
const x = 5;
x = 10; // Error! constant cannot be changed.
console.log(x)
Run Co
Also, you cannot declare a constant without initializing it. For example,
Note: If you are sure that the value of a variable won't change throughout the
program, it's recommended to use const .
JavaScript Function
Suppose you need to create a program to create a circle and color it. You can
create two functions to solve this problem:
• a function to draw the circle
Dividing a complex problem into smaller chunks makes your program easy to
understand and reusable.
Declaring a Function
function nameOfFunction () {
// function body
}
For example,
Calling a Function
// function call
greet();
Function Parameters
// calling functions
add(3,4);
add(2,9);
In the above program, the add function is used to find the sum of two numbers.
• The function is declared with two parameters a and b .
• The function is called using its name and passing two arguments 3 and 4 in
one and 2 and 9 in another.
Notice that you can call a function as many times as you want. You can write
one function and then call it multiple times with different arguments.
Function Return
The return statement can be used to return the value to a function call.
The return statement denotes that the function has ended. Any code
after return is not executed.
If nothing is returned, the function returns an undefined value.
Function Expressions
In the above program, variable x is used to store the function. Here the
function is treated as an expression. And the function is called using the
variable name.
The function above is called an anonymous function.
Scope refers to the availability of variables and functions in certain parts of the
code.
1. Global Scope
2. Local Scope
function greet() {
a = 3;
}
Then the variable a is accessed inside a function and the value changes to 3.
Hence, the value of a changes after changing it inside the function.
Note: It is a good practice to avoid using global variables because the value of
a global variable can change in different areas in the program. It can introduce
unknown results in the program.
For example,
function greet() {
a = "hello"
}
greet();
console.log(a); // hello
Local Scope
A variable can also have a local scope, i.e it can only be accessed within a
function.
function greet() {
let b = "World"
console.log(a + b);
}
greet();
console.log(a + b); // error
The let keyword is block-scoped (variable can be accessed only in the immediate
block).
function greet() {
// local variable
let b = 'World';
if (b == 'World') {
// block-scoped variable
let c = 'hello';
This function
// function expression
let x = function(x, y) {
return x * y;
}
can be written as
Here,
If a function doesn't take any argument, then you should use empty
parentheses. For example,
If a function has only one argument, you can omit the parentheses. For
example,
You can also dynamically create a function and use it as an expression. For
example,
let age = 5;
welcome(); // Child
If a function body has multiple statements, you need to put them inside curly
brackets {} . For example,
// return sum
return x + y;
}
console.log(sum(5, 15)); // 20
console.log(sum(7)); // 12
console.log(sum()); // 8
R
In the above example, the default value of x is 3 and the default value
of y is 5.
• sum(5, 15) - When both arguments are passed, x takes 5 and y takes 15.
• sum(7) - When 7 is passed to the sum() function, x takes 7 and y takes default
value 5.
• sum() - When no argument is passed to the sum() function, x takes default
value 3 and y takes default value 5.
Using Expressions as Default Values
sum(); // 4
If you reference the parameter that has not been initialized yet, you will
get an error. For example,
function sum( x = y, y = 1 ) {
console.log( x + y);
}
sum();
// object
const student = {
firstName: 'khan',
class: 12
};
Here, student is an object that stores values such as strings and numbers.
JavaScript Object Declaration
The syntax to declare an object is:
const object_name = {
key1: value1,
key2: value2
}
For example,
// object creation
const person = {
name: 'Hassan',
age: 20
};
console.log(typeof person); // object
JavaScript Object Properties
let person = {
name: 'Ali',
age: 20
};
objectName.key
For example,
const person = {
name: 'khan',
age: 20,
};
// accessing property
console.log(person.name); // khan
2. Using bracket Notation
objectName["propertyName"]
For example,
const person = {
name: 'khan',
age: 20,
};
// accessing property
console.log(person["name"]); // khan
// nested object
const student = {
name: 'ali',
age: 20,
marks: {
science: 70,
math: 75
}
}
const person = {
name: 'khan',
age: 30,
// using function as a value
greet: function() { console.log('hello') }
}
person.greet(); // hello
JavaScript Arrays
An array is an object that can store multiple values at once. For example,
Create an Array
The easiest way to create an array is by using an array literal [] . For example,
// empty array
const myList = [ ];
// array of numbers
const numberArray = [ 2, 4, 6, 8];
// array of strings
const stringArray = [ 'eat', 'work', 'sleep'];
You can also store arrays, functions and other objects inside an array. For
example,
const newData = [
{'task1': 'exercise'},
[1, 2 ,3],
function hello() { console.log('hello')}
];
You can access elements of an array using indices (0, 1, 2 …). For example,
const myArray = ['h', 'e', 'l', 'l', 'o'];
// first element
console.log(myArray[0]); // "h"
// second element
console.log(myArray[1]); // "e"
You can use the built-in method push() and unshift() to add elements to an
array.
The push() method adds an element at the end of the array. For example,
let dailyActivities = ['eat', 'sleep'];
The unshift() method adds an element at the beginning of the array. For
example,
let dailyActivities = ['eat', 'sleep'];
You can also add elements or change the elements by accessing the index
value.
You can use the pop() method to remove the last element from an array.
The pop() method also returns the returned value. For example,
let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];
If you need to remove the first element, you can use the shift() method.
The shift() method removes the first element and also returns the removed
element. For example,
let dailyActivities = ['work', 'eat', 'sleep'];
Array length
You can find the length of an element (the number of elements in an array)
using the length property. For example,
In JavaScript, there are various array methods available that makes it easier
to perform useful calculations.
Method Description
find() returns the first value of an array element that passes a test
findIndex() returns the first index of an array element that passes a test
aads a new element to the end of an array and returns the new length of a
push()
array
adds a new element to the beginning of an array and returns the new lengt
unshift()
of an array
pop() removes the last element of an array and returns the removed element
shift() removes the first element of an array and returns the removed element
slice() selects the part of an array and returns the new array
JavaScript forEach()
The forEach() method calls a function and iterates over the elements of an
array. The forEach() method can also be used on Maps and Sets.
JavaScript forEach
Here,
// using forEach
students.forEach(myFunction);
function myFunction(item) {
console.log(item);
}
Output
ali
hassan
saeed
Updating the Array Elements
// using forEach
students.forEach(myFunction);
console.log(students);
Output
You can use the arrow function with the forEach() method to write a program.
For example,
// with arrow function and callback
students.forEach(element => {
console.log(element);
});
In each iteration of the loop, a key is assigned to the key variable. The loop
continues for all object properties.
// using for...in
for ( let key in student ) {
String interpolation
Without template literals, when you want to combine output from expressions
with strings, you'd concatenate them using the addition operator +:
const a = 5;
const b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."
That can be hard to read – especially when you have multiple expressions.
With template literals, you can avoid the concatenation operator — and
improve the readability of your code — by using placeholders of the
form ${expression} to perform substitutions for embedded expressions:
const a = 5;
const b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."
Spread Operator
You can also use the spread syntax ... to copy the items into a single array.
For example,
const arr1 = ['one', 'two'];
const arr2 = [...arr1, 'three', 'four', 'five'];
console.log(arr2);
// Output:
// ["one", "two", "three", "four", "five"]
console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 2, 3]
console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 3, 4]
Here, both variables arr1 and arr2 are referring to the same array. Hence the
change in one variable results in the change in both variables.
However, if you want to copy arrays so that they do not refer to the same
array, you can use the spread operator. This way, the change in one array is
not reflected in the other. For example,
console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 2, 3]
console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 3]
You can also use the spread operator with object literals. For example,
const obj1 = { x : 1, y : 2 };
const obj2 = { z : 3 };
console.log(obj3); // {x: 1, y: 2, z: 3}
Rest Parameter
You can also accept multiple arguments in a function call using the rest
parameter. For example,
func(3); // [3]
func(4, 5, 6); // [4, 5, 6]
Here,
• When a single argument is passed to the func() function, the rest parameter
takes only one parameter.
• When three arguments are passed, the rest parameter takes all three
parameters.
You can also pass multiple arguments to a function using the spread operator.
For example,
sum(...num1); // 8
If you pass multiple arguments using the spread operator, the function takes
the required arguments and ignores the rest.
JavaScript Destructuring
The destructuring assignment introduced in ES6 makes it easy to assign array values
and object properties to distinct variables. For example,
Without Destructuring:
// assigning object attributes to variables
const person = {
name: 'Khadija',
age: 25,
gender: 'female'
}
console.log(name); // Khadija
console.log(age); // 25
console.log(gender); // female
Using Destructuring :
// assigning object attributes to variables
const person = {
name: 'Khadija',
age: 25,
gender: 'female'
}
// destructuring assignment
let { name, age, gender } = person;
console.log(name); // Khadija
console.log(age); // 25
console.log(gender); // female
Note: The order of the name does not matter in object destructuring.
For example,
If you want to assign different variable names for the object key, you can use:
Note: When destructuring objects, you should use the same name for the
variable as the corresponding object key.
const person = {
name: 'Khadija',
age: 25,
gender: 'female'
}
// destructuring assignment
// using different variable names
let { name: name1, age: age1, gender:gender1 } = person;
console.log(name1); // Khadija
console.log(age1); // 25
console.log(gender1); // female
The keys of hero are ['name', 'city']. The values are [Hassan', 'Rawalpindi]. And the
entries are [['name', 'Hassan], ['city', 'Rawalpindi]].
Let's see what utility functions provide JavaScript to extract the keys, values, and
entries from an object.
Object.keys()
Object.keys(object) is a utility function that returns the list of keys of object.
const person = {
name: 'Hassan',
city: 'Rawalpindi'
};
Object.keys(person); // => ['name', 'city']
Object.keys(person) returns the list ['name', 'city'], which, as expected, are the keys of person object.
Object.values()
Object.values(object) is the JavaScript utility function that returns the list of values of object.
Object.entries()
Object.entries(object) is an useful function to access the entries of object.
Let's extract the entries of person object:
const person = {
name: 'Hassan',
city: 'Rawalpindi'
};
Object.entries(person); // => [['name','Hassan'],['city','Rawalpindi']]
Array Destructuring
You can also perform array destructuring in a similar way. For example,
console.log(x); // one
console.log(y); // two
console.log(z); // three
Assign Default Values
You can assign the default values for variables while using destructuring. For
example,
console.log(x); // 10
console.log(y); // 7
const person = {
name: 'Ali',
}
console.log(name); // Ali
console.log(age); // 26
Swapping Variables
let x = 4;
let y = 7;
// swapping variables
[x, y] = [y, x];
console.log(x); // 7
console.log(y); // 4
Run Code
Skip Items
You can skip unwanted items in an array without assigning them to local
variables. For example,
console.log(x); // one
console.log(z); // three
Run Co
In the above program, the second element is omitted by using the comma
separator , .
You can assign the remaining elements of an array to a variable using the
spread syntax ... . For example,
const arrValue = ['one', 'two', 'three', 'four'];
// destructuring assignment in arrays
// assigning remaining elements to y
const [x, ...y] = arrValue;
console.log(x); // one
console.log(y); // ["two", "three", "four"]
Run Co
Here, one is assigned to the x variable. And the rest of the array elements are
assigned to y variable.
You can also assign the rest of the object properties to a single variable. For
example,
const person = {
name: ' Khadija ',
age: 25,
gender: 'female'
}
// destructuring assignment
// assigning remaining properties to rest
let { name, ...rest } = person;
console.log(name); // Khadija
console.log(rest); // {age: 25, gender: "female"}
R
Note: The variable with the spread syntax cannot have a trailing comma , .
You should use this rest element (variable with spread syntax) as the last
variable.
For example,
// throws an error
const [ ...x, y] = arrValue;
console.log(x); // error
Map
The map() method is used for creating a new array from an existing one,
applying a function to each one of the elements of the first array.
Syntax
var new_array = arr.map(function callback(element, index, array) {
// Return value for new_array
}[, thisArg])
In the callback, only the array element is required. Usually some action is
performed on the value and then a new value is returned.
Example
In the following example, each number in an array is doubled.
Filter
The filter() method takes each element in an array and it applies a
conditional statement against it. If this conditional returns true, the element
gets pushed to the output array. If the condition returns false, the element
does not get pushed to the output array.
Syntax
var new_array = arr.filter(function callback(element, index, array) {
// Return true or false
}[, thisArg])
The syntax for filter is similar to map, except the callback function should
return true to keep the element, or false otherwise. In the callback, only
the element is required.
Examples
In the following example, odd numbers are "filtered" out, leaving only even
numbers.
In the next example, filter() is used to get all the students whose grades
are greater than or equal to 90.
const students = [
{ name: 'ali', grade: 96 },
{ name: 'hamid', grade: 84 },
{ name: 'nasir', grade: 100 },
{ name: 'noman', grade: 65 },
{ name: 'anas', grade: 90 }
];
Syntax
arr.reduce(callback[, initialValue])
The callback argument is a function that will be called once for every item in
the array. This function takes four arguments, but often only the first two are
used.
• accumulator - the returned value of the previous iteration
• currentValue - the current item in the array
• index - the index of the current item
• array - the original array on which reduce was called
• The initialValue argument is optional. If provided, it will be used as
the initial accumulator value in the first call to the callback function.
Examples
The following example adds every number together in an array of numbers.
console.log(petCounts);
/*
Output:
{
dog: 2,
chicken: 3,
cat: 1,
rabbit: 1
}
*/
Ternary Operator
JavaScript Modules
As our program grows bigger, it may contain many lines of code. Instead of
putting everything in a single file, you can use modules to separate codes in
separate files as per their functionality. This makes our code organized and
easier to maintain.
Module is a file that contains code to perform a specific task. A module may
contain variables, functions, classes etc. Let's see an example,
// exporting a function
export function sayHello(name) {
return `Hello ${name}`;
}
Now, to use the code of Hello.js in another file, you can use the following
code:
// importing greetPerson from greet.js file
import { SayHello } from './Hello.js';
Here,
• The sayHi() function in the Hello.js is exported using the export keyword
• Then, we imported sayHi() in another file using the import keyword. To import
functions, objects, etc., you need to wrap them around { }.
You can only access exported functions, objects, etc. from the module. You
need to use the export keyword for the particular function, objects, etc. to
import them and use them in other files.
You can export members one by one. What’s not exported won’t be available
directly outside the module:
Default export
You can define a default export with the default keyword:
export const myNumbers = [1, 2, 3, 4];
const animals = ['Panda', 'Bear', 'Eagle'];
1. React Native
2. JSX
3. Components
4. Text and View Components
5. State and props
6. useState hook
7. Button Component
8. StyleSheet Object
9. Flex Design
React Native
React Native is the most popular library for developing cross-platform mobile
applications. This framework has made it possible to create native mobile apps for
multiple platforms simultaneously. You can develop full-blown mobile
applications for both iOS and Android using a single language, i.e., JavaScript.
This is a huge advantage, as it saves a lot of time and money and also eliminates
the steep learning curves that are associated with each platform’s native
development language (Java or Kotlin for Android, and C or C++ for iOS).
React Native applications are real mobile applications and not just web applets.
Facebook released the first version of React Native in March 2015.
Why Use React Native?
• Cross-Platform
One of the most significant advantages of React Native is that you can develop
an application for both Android and iOS ecosystems simultaneously by writing
the same code with just a few modifications for each platform.
• JavaScript
• Performance
A huge developers’ community ensures that all the queries are resolved in time,
and therefore, adequate support is available for the React Native framework.
The community, as mentioned above, also keeps updating React Native with
new functionalities and making sure that bugs do not occur.
• Used by Many Companies
React Native has become very popular lately due to advantages like cross-
compatibility. Consequently, this popularity has led to high demand for React
Native developers.
Environment Setup
Follow this guide to setup React Native in your machine:
https://reactnative.dev/docs/environment-setup
Introducing JSX
To understand the concept of JSX you should have an understanding of HTML.
You can visit following website to get knowledge of HTML
https://www.w3schools.com/html/
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
<Text>
Hello, {formatName(user)}! </Text>
);
Components
React Native provides various built-in components. Through components, one can
break the UI into reusable, independent pieces, and can think about each piece in
isolation. The components in React Native are defined as functions or
classes. Conceptually, components are like JavaScript functions. They accept
arbitrary inputs (called “props”) and return React elements describing what should
appear on the screen.
First of all, we need to import React to be able to use JSX, which will then be
transformed to the native components of each platform. On line 2, we import
the Text and View components from react-native.
Both <Text> and <View> components have style props where you can set colors,
sizes, etc. However, there are some important distinctions to keep in mind.
Although View does work similarly to a div element, you can’t wrap any text in it,
like this <View>this text doesn't work</View> (not that you should with
a div element anyway). That would cause an exception and that is why we use
the <Text> component.
The first style (used in view) that we find is flex: 1, the flex prop will define how
your items are going to "fill" over the available space along your main axis. Since
we only have one container, it will take all the available space of the parent
component. In this case, it is the only component, so it will take all the available
screen space.
When <Text> is wrapping <Text>, the nested text will come out on the same line,
assuming there is enough space. However, if the two <Text> components were
wrapped in a <View>, they would appear on separate lines.
So the above code is defining App, a new Component. When you're building a
React Native app, you'll be making new components a lot. Anything you see on the
screen is some sort of component.
Props
Most components can be customized when they are created, with different
parameters. These creation parameters are called props.
Your own components can also use props. This lets you make a single component
that is used in many different places in your app, with slightly different properties
in each place. Refer to props.YOUR_PROP_NAME in your functional components
or this.props.YOUR_PROP_NAME in your class components. Here's an example:
The other new thing going on here is the View component. A View is useful as a
container for other components, to help control style and layout.
With props and the basic Text, Image, and View components, you can build a
wide variety of static screens. To learn how to make your app change over time,
you need to learn about State.
State
Unlike props that are read-only and should not be modified, the state allows
React components to change their output over time in response to user actions,
network responses and anything else.
What's the difference between state and props in React?
In a React component, the props are the variables that we pass from a parent
component to a child component. Similarly, the state are also variables, with the
difference that they are not passed as parameters, but rather that the component
initializes and manages them internally.
import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
return (
<View style={styles.container}>
<Text>You clicked {count} times</Text>
<Button
onPress={() => setCount(count + 1)}
title="Click me!"
/>
</View>
);
};
useState Hook
useState is a Hook that allows you to have state variables in functional
components. You pass the initial state to this function and it returns a variable with
the current state value (not necessarily the initial state) and another function to
update this value.
Remember that useState returns an array, where the first element is the state
variable and the second element is a function to update the value of the variable:
const Message= () => {
const messageState = useState( '' );
const message = messageState[0]; // Contains ''
const setMessage = messageState[1]; // It’s a function
}
Usually, you’ll use array destructuring to simplify the code shown above:
const Message= () => {
const [message, setMessage]= useState( '' );
}
The second element returned by useState is a function that takes a new value to
update the state variable.
<View>
}
Button Component
React Native Button is a basic component that works by clicking on it. There are
combinations of gestures that work on it, such as tapping on the button, zooming
the map, scrolling a list, etc. A button is one of the components that work on its
click.
React Native Button component imports the Button class of react-native library. It
has several props such as title, onPress, accessibilityLabel, etc. which are
mentioned above.
The minimal example to display a button looks like this:
<Button
onPress={() => {
alert('You tapped the button!');
}}
title="Press Me"
/>
Pressing the button will call the "onPress" function, which in this case displays an
alert popup.
Flex Design
A component can specify the layout of its children using the Flexbox algorithm.
Flexbox is designed to provide a consistent layout on different screen sizes.
flex will define how your items are going to “fill” over the available space along
your main axis. Space will be divided according to each element's flex property.
https://reactnative.dev/docs/flexbox
https://blog.logrocket.com/using-flexbox-react-native/
WEEK #4
1. Text Input
2. Radio Button
3. Check Box
4. React Native Picker
Here’s the code for the React Native Radio button example:
import * as React from 'react';
import { RadioButton } from 'react-native-paper';
import{View,Text} from 'react-native'
A check box, selection box, or tick box is a small interactive box that can be toggled
by the user to indicate an affirmative or negative choice. It is frequently found
in HTML input forms, dialog boxes, and in the GUIs of applications and operating
systems.
Let’s take a look at how to create checkboxes in React Native.
For information about React Native checkbox properties visit following link
https://github.com/react-native-checkbox/react-native-checkbox
}))}
/>
<Text>React js</Text>
</View>
<View style={styles.checkboxWrapper}>
<CheckBox
value={state.next}
onValueChange={value =>
setState({
...state,
next: value,
})
}
/>
<Text>Next js</Text>
</View>
<View style={styles.checkboxWrapper}>
<CheckBox
value={state.vue}
onValueChange={value =>
setState({
...state,
vue: value,
})
}
/>
<Text>Vue js</Text>
</View>
<View style={styles.checkboxWrapper}>
<CheckBox
value={state.angular}
onValueChange={value =>
setState({
...state,
angular: value,
})
}
/>
<Text>Angular js</Text>
</View>
</View>
<Button
onPress={() => setToggleButton(toggleButton =>
!toggleButton)}
title="Save"
/>
</View>
{
toggleButton && (
<View style={styles.resultContainer}>
{Object.entries(state).map(([key, value]) => {
return (
value && (
<View key={key} style={{paddingHorizontal:
5}}>
<Text>{key}</Text>
</View>
));
})}
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
textInput: {
borderColor: 'gray',
borderWidth: 1,
},
resultContainer: {
flexDirection: 'row',
padding: 10,
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
checkboxWrapper: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 5,
},
});
Say, for instance, in payment you want to ask a user to select in which currency they
want to pay you, it makes sense to render as many currencies as possible depending
on the scope of your user base. Let’s see how we can achieve that using the React
Native picker component!
First off, install the React Native Picker by running npm install @react-native-
picker/picker --save
Here’s the code for the React Native Picker example:
Touchable Opacity
A wrapper for making views respond properly to touches. On press down, the
opacity of the wrapped view is decreased, dimming it.Opacity is controlled by
wrapping the children in an Animated.View, which is added to the view hierarchy.
Be aware that this can affect layout.In simple words, when you use any component
in Touchableopacity then you realize icon has pressed down.
The TouchableOpacity wrapper is used to reduce the opacity of button. It allows
background to be seen while the user press down. The opacity of button will be
controlled by wrapping the children in an Animation.
Syntax
Here's the syntax of TouchableOpacity.
<TouchableOpacity onPress={ //callback function }>
<Text>Press Here</Text>
</TouchableOpacity>
Props
• onPress, it will render the items, and accepts a callback function.
• activeOpacity, the opacity of wrapped view when it is touched.
• hitSlop , this defines how far your touch can start away from the button.
Code Example
You can use styles and other props according to your app needs.
To read more about TouchableOpacity, visit the following links.
https://reactnative.dev/docs/touchableopacity
https://www.javatpoint.com/react-native-
touchables#:~:text=React%20Native%20TouchableOpacity,the%20children%20in
%20an%20Animation.
Pressable
Pressable is a Core Component wrapper that can detect various stages of press
interactions on any of its defined children.
Pressable responds to touch, mouse, and keyboard interactions. The interaction state
of the view is exposed to the children and style props which accept a callback as
their value. The hover state is only activated by mouse interactions.
Syntax
<Text>I am pressable!</Text>
</Pressable>
Props
• onPressIn, is called when a press is activated.
• onPressOut, is called when the press gesture is deactivated.
How it works
1. The person will remove their finger, triggering onPressOut followed
by onPress.
2. If the person leaves their finger longer than 500 milliseconds before
removing it, onLongPress is triggered. (onPressOut will still fire when they
remove their finger.)
Code Example
Components?
Pressable component has all the features of Touchable components. Therefore, we
can replace all TouchableOpacity, TouchableHighlight, TouchableNativeFeedback
and TouchableWithoutFeedback with a single component.
To read more about Pressable, visit the following link:
https://reactnative.dev/docs/pressable
Scroll View
The ScrollView is a generic scrolling container that can contain multiple
components and views. The scrollable items can be heterogeneous, and you can
scroll both vertically and horizontally (by setting the horizontal property).
To scroll its components in horizontal, it uses the props horizontal: true (default,
horizontal: false).
Syntax
<ScrollView>
// everything inside here will be scrollable
</ScrollView>
Props
There are many props to Scroll View. Some of them are:
scrollEnabled When false, the view cannot be scrolled via touch interaction.
horizontal When true, the scroll view's children are arranged horizontally in a row
instead of vertically in a column.
Code Example
marginHorizontal: 20,
},
text: {
fontSize: 42,
},
});
Syntax
Here’s the syntax of FlatList
import { FlatList } from "react-native";
<FlatList
data={
//the array to render
}
keyExtractor={
// Extract keys for each item in the array
}
renderItem={
//each item from the array will be rendered here
}
/>
Props
• In the data prop, you will enter the array that you want to display.
• The keyExtractor prop to specify which piece of data should be used as the
key.
• renderItem will tell React Native how to render the items from the list. It
accepts a callback function
Code Example
Here’s the basic code for the React Native FlatList example:
import React from 'react';
import { StyleSheet, Text, View, FlatList } from 'react-native';
<View style={styles.item}>
<Text style={styles.text}>{item.name}</Text>
</View>
)}
/>
</View>
);
};
A better approach would be to create a callback function for the renderItem prop
like this
Styles will remain the same for the above code example
https://blog.logrocket.com/deep-dive-react-native-flatlist/
https://reactnative.dev/docs/flatlist
SectionList
SectionList enables you to show a sectioned list in your UI. It is a performant
interface for rendering sectioned lists with useful features, including scroll loading,
pull to refresh, section separator support, etc.
Syntax
Here’s the syntax for SectionList
import { SectionList } from "react-native";
<SectionList
sections={
// array of data (with different objects for different sections) that is
to be rendered.
}
keyExtractor={
// used to extract a unique key for a particular item in the list
}
renderItem={
// each item from the array will be rendered here
}
renderSectionHeader={
// It is rendered at the top of every section.
}
/>
Props
• In the section prop, you will enter the array that you want to display.
• The keyExtractor prop to specify which piece of data should be used as the
key.
• renderItem will tell React Native how to render the items from the list. It
accepts a callback function
• renderSectionHeader will be rendered on top of every section.
Code Example
Here’s the basic code for the React Native SectionList example:
import React from "react";
import { StyleSheet, Text, View, SectionList,} from "react-native";
const data = [
{
title: "Main dishes",
data: ["Pizza", "Burger", "Risotto"]
},
{
title: "Sides",
data: ["French Fries", "Onion Rings", "Fried Shrimps"]
},
{
title: "Drinks",
data: ["Water", "Coke", "Beer"]
},
{
title: "Desserts",
data: ["Cheese Cake", "Ice Cream"]
}
];
https://reactnative.dev/docs/sectionlist
https://blog.logrocket.com/react-native-sectionlist-tutorial-examples/
Refresh Control
Refresh Control Pull-to-refresh is a touchscreen gesture that retrieves all the latest
data and updates the currently available data in the app. You initiate it by swiping
down from the top of the screen. This action will load new data from the server and
display it in the interface. React Native provides individual RefreshControl
component specifically to implement pull-to-refresh easily in a React Native app.
Syntax
Here’s the syntax for Refresh Control
import { RefreshControl } from "react-native";
<RefreshControl
refreshing={
// a boolean that indicates whether the data is currently being refreshed.
}
onRefresh={
// This is a function that gets executed when refresh starts.
}
/>
Props
• In the refreshing prop, you will enter the array that you want to display.
• The onRefresh prop is a function that gets executed when refresh starts. This
function should usually set refreshing to true when it starts and false once it
completes.
Code Example
Here’s the basic code for the React Native RefreshControl example:
import React, { useState } from 'react';
import { RefreshControl, StyleSheet, Text, FlatList, View } from 'react-native';
const App = () => {
const [refreshing, setRefreshing] = useState(false);
let countries = [
{ id: 1, name: 'Pakistan' },
{ id: 2, name: 'United States of America' },
{ id: 3, name: 'Oman' },
{ id: 4, name: 'Morocco' },
{ id: 5, name: 'Spain' },
{ id: 6, name: 'Germany' },
{ id: 7, name: 'Japan' },
{ id: 8, name: 'China' },
{ id: 9, name: 'Taiwan' },
{ id: 10, name: 'South Korea' },
];
return (
<View style={styles.container}>
<FlatList
data={countries}
keyExtractor={(item) => item.id}
renderItem={ShowItem}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
margin: 30,
marginTop: 50,
},
item: {
backgroundColor: '#FF5858',
padding: 20,
marginBottom: 50,
borderRadius: 12,
},
text: {
fontSize: 24,
textAlign: 'center',
color: 'white',
},
});
https://reactnative.dev/docs/refreshcontrol
https://blog.expo.dev/react-native-pull-to-refresh-make-refreshing-easy-for-users-
813088732c4f
WEEK #6
1. Intro to useEffect Hook
2. Intro to SQLite
3. Installation of SQLite
4. SQLite Basic Queries
5. How to use SQLite?
6. SQLite CRUD App
Syntax
The second argument is an array, called the dependencies array. This array should
include all of the values that our callback function relies upon. If any of the values
in the dependency array changes, it will fire the callback function.
Code Examples
Let’s take a look at some examples
useEffect(() => {
setCount(count + 1);
}, []);
return (
<View>
<Text>Count: {count}</Text>
</View>
);
};
export default App;
In the above example the callback function of useEffect will run when the
component first renders and it will change the count from to 0 to 1. And the
callback function will run only once. Why? Because the dependency array is
empty.
If you don’t add the dependency array as the second argument of useEffect, it’ll
create a never-ending loop which will obviously affect your app performance or
even crashes the app.
useEffect(() => {
setSquareCount(count * count);
}, [count]);
return (
<View>
<Text>Count: {count}</Text>
<Text>Square: {squareCount}</Text>
<Button title="Increment" onPress={incrementCount} />
</View>
);
};
So, when the component first renders the useEffect hook will run and set the
squareCount value to 0, when the count value changes, the callback function of
useEffect runs again and recalculate the squareCount value.
Intro to SQLite
Installation of SQLite
To install SQLite, run the following command in terminal:
SELECT QUERY
SELECT * FROM Users
INSERT QUERY
INSERT INTO Users VALUES(1, 'Ali', 'Rawalpindi')
DELETE QUERY
DELETE FROM Users WHERE id = 1
UPDATE QUERY
UPDATE Users SET name = ‘Amjad’ WHERE id = 1
You can now use the db variable to execute a database query whenever you need to
make a database call.
db.transaction((txn) => {
txn.executeSql(
query, //Query to execute
argsToBePassed[], // Arguments to pass
(tx, res) => {}, // Callback function to handle the
response
(error) => {} // Callback function to handle the error
);
});
function updateWish() {
db.transaction((txn) => {
txn.executeSql(
`update wishlist set name=? where id=? `,
[name, wishid],
(sqltxn, res) => {
Alert.alert('Success', 'Wish Update Successfully..');
setWishId(0);
setName('');
setButtonTitle('Add Wish');
fetchWishList();
},
(error) => {
console, log('Error occured during Adding WishList...');
}
);
});
}
function AddWish() {
console.log('Execution Started...', name);
db.transaction((txn) => {
txn.executeSql(
`insert into wishlist (name) values(?) `,
[name],
(sqltxn, res) => {
console.log(res);
setWishId(0);
setName('');
fetchWishList();
},
(error) => {
console, log('Error occured during Adding WishList...');
}
);
});
}
function saveWish() {
if (!name) {
Alert.alert('Warning', 'Enter Wish List');
return false;
}
if (buttonTitle === 'Add Wish') {
AddWish();
} else {
updateWish();
}
}
function editWish({ item }) {
console.log('edit item name', item.name);
console.log('edit item id', item.id);
setWishId(item.wishId);
setName(item.name);
setButtonTitle('Update Wish');
}
function deleteWishList(id) {
db.transaction((txn) => {
txn.executeSql(
`delete from wishlist where id=?`,
[id],
(sqltxn, res) => {
Alert.alert('Success...', 'Wish Deleted Successfully..');
fetchWishList();
},
(error) => {
Alert.alert('Error', 'Error occured during Wish Deletion...');
}
);
});
}
return (
<View style={myStyles.container}>
<Text style={{ fontSize: 16 }}> Enter Value</Text>
<TextInput
placeholder="Enter Wishlist"
style={myStyles.input}
value={name}
onChangeText={(value) => setName(value)}
/>
<Button title={buttonTitle} onPress={saveWish} />
<Text style={{ fontSize: 20, fontFamily: 'arial' }}>
WishList Details
</Text>
<FlatList
data={wishlist}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<View style={{ backgroundColor: 'yellow', height: 50, margin: 10 }}>
<TouchableOpacity onPress={() => deleteWishList(item.id)}>
<Text style={{ color: 'black', fontSize: 17 }}>{item.name}</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => editWish({ item })}>
<Text style={myStyles.button}>Edit</Text>
</TouchableOpacity>
</View>
)}
/>
</View>
);
}
WEEK #7
1. Intro to React Navigation
2. Installation of React Navigation
3. Working with Stack Navigation
4. Passing parameters to routes
5. Working with Tab Navigation
Intro to React Navigation
React Native Navigation is used for managing the presentation, and transition
between multiple screens. There are two types of navigation built in mobile
applications. These are stack navigation and tabbed navigation patterns.
For example, if you navigate from login to signup screen, the signup screen is
stacked on top of the login screen, and if you navigate back, the signup screen is
then popped off the stack.
To create stack navigation, install the required library by running the following
command
npm install @react-navigation/stack
npm install react-native-gesture-handler
import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
In the above example, I have created two components named Home & About with
some boilerplate code and imported them in App.js. initialRouteName prop
will render the Home component on first load of the navigator.
To pass parameters, put all the data that you want to pass in an object as a second
parameter to the navigation.navigate function
To access the data passed from Home to About screen, you would use route prop
In the above example, I have created two components named HomeScreen &
AboutScreen with some boilerplate code in App.js. A better practice would be to
create these components in their own separate files.
WEEK #8
1. Alert
2. Modal,
3. Image
4. Image Background
5. Toast
Alert
The Alert dialog is used to show the message to the user. Usually, it is a dialog or
popup that appears with a message and title on clicking on a button or loading or
redirecting to a particular page in an application. Following are the different type of
Alerts in React Native:
• Simple Alert.
• Two Option Alert.
• Three Option.
Syntax
Alert.alert('Heading', 'Body', [
// 👇 Object contains info about button
{
text: 'OK',
onPress: () => console.log('pressed'),
},
]);
How to create a simple alert
When you click outside of alert area, it gets cancelled. To alter this behavior of
alert, we can use this cancelable object
https://reactnative.dev/docs/alert
Modal
Modals are separate windows within an application, most often as a dialog box.
They are a common user interface pattern for providing information or requiring
confirmation.
Syntax
<Modal
animationType="slide"
transparent={
// determines whether your modal will fill the entire view
}
visible={
// determines whether your modal is visible
}
onRequestClose={
// callback function which runs when the user the back button on
Android
}>
// everything here will be rendered
</Modal>
Props
• The animationType prop controls how the modal animates. Possible
values are 'none', 'slide', & 'fade'
• The transparent prop determines whether your modal will fill the entire
view. Setting this to true will render the modal over a transparent
background.
• The visible prop determines whether your modal is visible
• The onRequestClose callback is called when the user taps the hardware
back button on Android or the menu button on Apple TV.
Code Example
import {StyleSheet, Text, View, Modal, TouchableOpacity,
Button} from 'react-native';
import React, {useState} from 'react';
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.button}
onPress={() => setModalVisible(!modalVisible)}>
<Text style={styles.text}>Press Me</Text>
</TouchableOpacity>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}>
<View style={styles.modal}>
<Text style={styles.text}>Modal is open!</Text>
<Button
title="Click To Close Modal"
onPress={() => {
setModalVisible(!modalVisible);
}}
/>
</View>
</Modal>
</View>
);
};
https://reactnative.dev/docs/modal
Image
A React component for displaying different types of images, including network
images, static resources, temporary local images, and images from local disk, such
as the camera roll.
Syntax
<Image
style={ // accepts styles here}
source={ // path of an image }
/>
Props
• source - the image source (either a remote URL or a local file resource).
• resizeMode - determines how to resize the image when the frame
doesn't match the raw image dimensions.
• opacity - Set an opacity value for the image. The number should be in the
range from 0.0 to 1.0.
Code Example
In this code example, we have an assets folder where we have an image named
“image.jpg”
https://reactnative.dev/docs/image
Image Background
A common feature request from developers familiar with the web is background-
image. To handle this use case, you can use the <ImageBackground> component,
which has the same props as <Image>, and add whatever children to it you would
like to layer on top of it.
Syntax
<ImageBackground
source={
// path of an image
}
resizeMode= "
// Resizing of image based on different mobile
configurations.
"
style={
// accepts styles here
}>
// anything inside here will have the background
Image
</ImageBackground>
Props
• source - the image source (either a remote URL or a local file resource).
• resizeMode - determines how to resize the image when the frame
doesn't match the raw image dimensions.
• opacity - Set an opacity value for the image. The number should be in the
range from 0.0 to 1.0.
Code Example
https://reactnative.dev/docs/imagebackground
Toast
A toast provides simple feedback about an operation in a small popup. It only fills
the amount of space required for the message and the current activity remains
visible and interactive. Toasts automatically disappear after a timeout.
Syntax
ToastAndroid.show(
// message
'My message',
// duration
ToastAndroid.LONG,
);
Properties
Code Example
};
return (
<View style={styles.container}>
<Button title="Toggle toast" onPress={handleToast} />
</View>
);
};
https://reactnative.dev/docs/toastandroid
WEEK #9
1. Image Picker
2. Storing image in Database
3. Material Top Tabs Navigation
4. Adding Icons to Navigation
Image Picker
In this React Native Image Picker tutorial, we are going to use a very well known
library called react-native-image-picker to choose the image from Gallery and
Camera.
This library is based on ImagePicker component that lets you use native UI to pick
a photo/video from the device library or directly from the camera, and it supports
both iOS and Android platforms very smoothly.
Now we have to add a few permissions for Android to access Android Camera
& Storage.
Let’s understand how to assign permissions for Android devices, and we are
about to use Native Camera to pick the image from the Gallery.
Go to React Native Project > android > app > src > debug
> AndroidManifest.xml file and include the given below permissions.
<uses-permission
android:name="android.permission.CAMERA"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission
android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission
android:name="android.permission.CAMERA"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:usesCleartextTraffic="true"
tools:targetApi="28"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name="com.facebook.react.devsupport.DevSettingsActiv
ity" android:exported="false" />
</application>
</manifest>
First, we have to import the these following methods from the ImagePicker
package at the top of the App.js file.
launchCamera
This method is used to take a photo or video.
launchImageLibrary
This method is used to launch gallery to pick an image or a video.
Now, replace the existing code of App.js file with the following code.
if (response.didCancel) {
alert('User cancelled camera picker');
return;
} else if (response.errorCode == 'camera_unavailable')
{
alert('Camera not available on device');
return;
} else if (response.errorCode == 'permission') {
alert('Permission not satisfied');
return;
} else if (response.errorCode == 'others') {
alert(response.errorMessage);
return;
}
console.log('Response again.. = ', response);
console.log('base64 -> ', response.assets[0].base64);
console.log('uri -> ', response.assets[0].uri);
console.log('width -> ', response.assets[0].width);
console.log('height -> ', response.assets[0].height);
console.log('fileSize -> ',
response.assets[0].fileSize);
console.log('type -> ', response.assets[0].type);
console.log('fileName -> ',
response.assets[0].fileName);
setFilePath(response.assets[0]);
});
};
return (
<View style={{flex: 1}}>
<Text style={styles.titleText}>Image Picker in React
Native</Text>
<View style={styles.container}>
<Text>Base64 Image</Text>
{
<Image
source={{
uri:
`data:${filePath.type};base64,${filePath.base64}`,
}}
style={styles.imageStyle}
/>
}
<Text>Uri Image</Text>
<Image source={{uri: filePath.uri}}
style={styles.imageStyle} />
<TouchableOpacity
activeOpacity={0.5}
style={styles.buttonStyle}
onPress={() => chooseFile('photo')}>
<Text style={styles.textStyle}>Choose Image</Text>
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.5}
style={styles.buttonStyle}
onPress={() => captureImage('photo')}>
<Text style={styles.textStyle}>Capture
Image</Text>
</TouchableOpacity>
</View>
</View>
);
};
requestCamerPermission
It’s an asynchronous function. and it’ll ask the user to grant camera permission
with the help of PermissionAndroid component that comes with react native. If
the user gives the permission, it’ll return true otherwise false
requestExternalWritePermission
It works the same way as requestCameraPermission but for WritePermission.
Add.js
import {StyleSheet, Text, View, Image, ToastAndroid} from 'react-native';
import React, {useState, useEffect} from 'react';
import {TextInput, Button} from 'react-native-paper';
import {launchImageLibrary} from 'react-native-image-picker';
import {openDatabase} from 'react-native-sqlite-storage';
const db = openDatabase({name: 'Users.db'});
useEffect(() => {
CREATE_TABLE();
// DROP_TABLE();
}, []);
<Button
mode="contained"
onPress={() => chooseFile('photo')}
style={styles.button}>
Choose Photo
</Button>
<Button mode="contained" onPress={handleAddUser} style={styles.button}>
Add User
</Button>
{/* For Debugging Purpose */}
<Button
mode="contained"
onPress={() => navigation.navigate('List')}
style={styles.button}>
Move to List
</Button>
</View>
);
};
List.js
import React, {useState, useEffect} from 'react';
import {StyleSheet, View, FlatList} from 'react-native';
import {Button, Card, Paragraph} from 'react-native-paper';
import {openDatabase} from 'react-native-sqlite-storage';
const db = openDatabase({name: 'Users.db'});
You've now successfully installed Material Top Tabs Navigation in your project.
Now let’s take a look at how we can work with it.
Here’s the App.js code
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createMaterialTopTabNavigator} from '@react-navigation/material-top-
tabs';
// Screens
import Home from './screens/Home';
import Register from './screens/Register';
import Login from './screens/Login';
import {View} from 'react-native';
Note: The difference between tabBarBadge property in Top & Bottom Tabs
Navigation is that top tab navigation accepts a function which returns something
like View, Text or whatever component you want to return and bottom tabs accepts
a string, number or a boolean value.
Adding icons to navigation
We have already discussed about how we can use Bottom Tabs Navigation in
Week 6. Now we’re going to learn how we can add icons to our navigation.
First, we need to add vector icons to our project by running the following npm
command.
npm install --save react-native-vector-icons
Now edit android > app > build.gradle file in your project and add the following
line
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
The setup is done now, let’s take a look at how we can add icons to our navigation
rather than using labels
Here’s the App.js code
// Screens
import Home from './screens/Home';
import Register from './screens/Register';
import Login from './screens/Login';
// Import Icons
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
const Tab = createMaterialTopTabNavigator();
const App = () => {
return (
<NavigationContainer>
<Tab.Navigator initialRouteName="Home">
<Tab.Screen
name="Home"
component={Home}
options={{
tabBarShowLabel: false,
tabBarIcon: () => {
return <FontAwesome5 name={'home'} size={24} solid />;
},
}}
/>
<Tab.Screen name="Login" component={Login} />
<Tab.Screen name="Register" component={Register} />
</Tab.Navigator>
</NavigationContainer>
);
};
In the above example, we have imported font awesome 5 icons and used it, here is
the link from where you can choose icons and use it in your application
Link: https://oblador.github.io/react-native-vector-icons/
Just make sure the icon you’re using is available in FontAwesome 5 section
When you find your desired icon just copy it’s name and add it to the name prop of
FontAwesome5 tag.
WEEK #10
1. Working with APIs
2. Fetching Data
3. POST Data
a. Query String
b. Object
c. Multipart Request
4. What is Async Storage
5. Async Storage Methods
There are multiple ways of requesting data from an API, but all of them basically
do the same thing. For the most part, APIs are accessed through URLs, and the
specifics of how to query these URLs change based on the specific service you are
using.
Fetching Data
There are multiple ways to fetch data from an API but the one we are going to use
is 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.
POST Data
There are multiple ways to POST data to an API but the one we are going to use is
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.
Query String
const handleAddProduct = async () => {
const response = await fetch(
`http://localhost/ProductsAPI/api/products/addproductbyquerystring?title=${
title}&price=${price}&stock=${stock}`,
{
method: 'POST',
}
);
const data = await response.json();
console.log(data);
};
Object
const handleAddProductByObject = async () => {
const response = await fetch(
`http://${IP}/ProductsAPI/api/products/addproductbyobject`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: title,
price: price,
stock: stock,
}),
}
);
const data = await response.json();
};
Multipart Request
const handleSaveImage = async () => {
// Image Data is an Object with the following properties
// uri: response.assets[0].uri,
// name: response.assets[0].fileName,
// type: response.assets[0].type,
try {
let data = new FormData();
data.append('name', name);
data.append('userID', userID);
data.append('image', imageData);
const requestOptions = {
method: 'POST',
body: data,
};
const response = await fetch(
`http://${IP}/FlowerAPITask/api/flowers/UploadFlower`,
requestOptions
);
const results = await response.json();
} catch (error) {
console.log(error);
}
};
Async Storage
AsyncStorage is a simple, asynchronous, unencrypted by default module that
allows you to persist data offline in React Native apps. The persistence of data is
done in a key-value storage system.
There are numerous scenarios where this module can be beneficial. Persisting data
in a mobile app has benefits such as when the user restarts the app, the data or the
setting variables being available to the user in the state they left before closing the
app. To install AsyncStorage, run the following command
npm install @react-native-async-storage/async-storage
getAllKeys()
const printAllKeys = async () => {
try {
keys = [];
keys = await AsyncStorage.getAllKeys();
console.log(keys);
} catch (e) {
console.log(e);
}
};
removeItem()
const removeItem = async () => {
try {
await AsyncStorage.removeItem('user');
} catch (e) {
console.log(e);
}
};
clear()
const clearAll = async () => {
try {
await AsyncStorage.clear();
} catch (e) {
console.log(e);
}
};
• Color Highlight
This extension styles css/web colors found in your document.
Helpful Commands
To list all android devices in your computer run following command
adb devices
To run react project (on android device) in your computer run following command
npx react-native run-android
reactjs.org
reactnavigation.org
developer.mozilla.org
www.w3schools.com
www.freecodecamp.org
www.programiz.com
medium.com
www.simplilearn.com
www.digitalocean.com
https://blog.logrocket.com/build-better-forms-with-react-native-ui-components/
Flex Quick Pictorial Review
React Native Coding Samples
return (
<View style={styles.body}>
<Text style={styles.text}>{name}</Text>
<Text style={styles.text}>This is session number
{session.number} and about {session.title}</Text>
<Text style={styles.text}>{current ? 'current Week' :
'next Week'}</Text>
<Button title='Modify State'
onPress={onClickHandler}></Button>
</View>
);
};
Type the give code and try to understand. Note that button component does not
contain Style prop. We have applied style on button with the help of view Component.
return (
<View style={styles.body}>
<Text style={styles.text}>{name}</Text>
<View style={styles.button}>
<Button title='Update State'
onPress={onClickHandler}></Button>
</View>
</View>
);
};
return (
<View style={styles.body}>
<View style={styles.container1}>
<Text style={styles.text}>One</Text>
</View>
<View style={styles.container2}>
<Text style={styles.text}>Two</Text>
</View>
<View style={styles.container3}>
<Text style={styles.text}>Three</Text>
</View>
</View>
);
};
const newTaskData = [
{
title: 'New Tasks',
data: [
{
id: '1',
task: 'Buy groceries',
},
{
id: '2',
task: 'Feed Cat',
},
{
id: '3',
task: 'Sleep for 3 hours',
},
{
id: '4',
task: 'Water Plants',
},
{
id: '5',
task: 'Drink Water',
},
],
},
];
const completedTaskData = [
{
title: 'Completed Tasks',
data: [
{
id: '6',
task: 'Make a section list tutorial',
},
{
id: '7',
task: 'Share this tutorial',
},
{
id: '8',
task: 'Ask doubt in the Comments',
},
{
id: '9',
task: 'Read next Article',
},
{
id: '10',
task: 'Read next Article 2',
},
{
id: '11',
task: 'Read next Article 3',
},
{
id: '12',
task: 'Read next Article 4',
},
{
id: '13',
task: 'Read next Article 5',
},
{
id: '14',
task: 'Read next Article 6',
},
{
id: '15',
task: 'Read next Article 7',
},
{
id: '16',
task: 'Read next Article 8',
},
{
id: '17',
task: 'Read next Article 9',
},
{
id: '18',
task: 'Read next Article 10',
},
{
id: '19',
task: 'Read next Article 11',
},
],
},
];
const Item = ({ item }) => {
return <Text style={styles.taskItem}>{item.task}</Text>;
};
return (
<View style={styles.rootContainer}>
<View style={styles.container}>
<SectionList
sections={[...newTaskData, ...completedTaskData]}
renderItem={Item}
renderSectionHeader={Header}
keyExtractor={(item, index) => index.toString()}
refreshControl={
<RefreshControl
//refresh control used for the Pull to Refresh
refreshing={refreshing}
onRefresh={onRefresh}
/>
}
stickySectionHeadersEnabled
/>
</View>
</View>
);
};
return (
<View style={styles.container}>
<Pressable
onPress={() => {
setTimesPressed((current) => current + 1);
}}
style={({ pressed }) => [
{
backgroundColor: pressed
? 'rgb(210, 230, 255)'
: 'white'
},
styles.wrapperCustom
]}>
{({ pressed }) => (
<Text style={styles.text}>
{pressed ? 'Pressed!' : 'Press Me'}
</Text>
)}
</Pressable>
<View style={styles.logBox}>
<Text testID="pressable_press_console">{textLog}</Text>
</View>
</View>
);
};
App.js
BookDetails.js
BookInfo.js
return (
<View style={styles.container}>
<FlatList
data={books}
keyExtractor={(item, index) => index}
renderItem={Item}
/>
</View>
);
};
App.js
NewPizza.js
TakeOrder.js
useEffect(() => {
FETCH_DISTINCT_FLAVOURS();
}, []);
useEffect(() => {
FETCH_DISTINCT_SIZES();
}, [selectedFlavour]);
useEffect(() => {
console.log(orders);
}, [orders]);
useEffect(() => {
let totalCurrentOrder = currentOrderPrice * quantity;
if (totalCurrentOrder) {
setTotalPrice(prev => prev + totalCurrentOrder);
}
setQuantity(0);
}, [currentOrderPrice]);
useEffect(() => {
console.log('USEEFFECT TOTAL PRICE: ', totalPrice);
}, [totalPrice]);