0% found this document useful (0 votes)
155 views182 pages

React Native Guide

The document provides an overview of essential JavaScript concepts for React including variables, data types, functions, scope, and arrow functions. It discusses the differences between var, let, and const, and covers function parameters, return values, and scope. The summary introduces JavaScript variables, functions, and arrow functions in 3 sentences: JavaScript variables can be declared using var, let, or const, and are used to store and manipulate data. Functions are blocks of code that perform tasks and can accept parameters and return values. Arrow functions introduced in ES6 provide a cleaner syntax for writing anonymous functions in JavaScript.

Uploaded by

khawajasoban13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
155 views182 pages

React Native Guide

The document provides an overview of essential JavaScript concepts for React including variables, data types, functions, scope, and arrow functions. It discusses the differences between var, let, and const, and covers function parameters, return values, and scope. The summary introduces JavaScript variables, functions, and arrow functions in 3 sentences: JavaScript variables can be declared using var, let, or const, and are used to store and manipulate data. Functions are blocks of code that perform tasks and can accept parameters and return values. Arrow functions introduced in ES6 provide a cleaner syntax for writing anonymous functions in JavaScript.

Uploaded by

khawajasoban13
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 182

React Native Guide

Prepared By: Muhammad. Aftab Khan


WEEK #1

Essential JavaScript for React Part 1


1. JavaScript Variables
2. let ,var and const keywords
3. Functions and Arrow Functions
4. Objects
5. Arrays and array methods

JavaScript Variables

There are four ways to declare a JavaScript Variable:


• Using var
• Using let
• Using const
• Using nothing

In programming, a variable is a container (storage area) to hold data. For


example,

• let num = 5;

Here, num is a variable. It's storing 5.


In JavaScript, we use either var or let keyword to declare variables. For
example,

var x;
let y;

Here, x and y are variables.


Both var and let are used to declare variables. However, there are some
differences between them.
Var Let

var is used in the older versions of let is the new way of declaring variables starting
JavaScript ES6 (ES2015).

var is function scoped let is block

For example, var x; For example, let y;

Variable declared by let cannot be redeclared and must be declared before use
whereas variables declared with var keyword are hoisted.

Rules for Naming JavaScript Variables

The rules for naming variables are:

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';

Variable names cannot start with numbers. For example,

5. //invalid
6. Let 1a = 'hello'; // this gives an error

JavaScript is case-sensitive. So y and Y are different variables. For example,

7. let y = "hi";
8. let Y = 5;
9.
10. console.log(y); // hi
11. console.log(Y); // 5

Keywords cannot be used as variable names. For example,

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;

Once a constant is initialized, we cannot change its value.

const x = 5;
x = 10; // Error! constant cannot be changed.
console.log(x)
Run Co

Simply, a constant is a type of variable whose value cannot be changed.

Also, you cannot declare a constant without initializing it. For example,

const x; // Error! Missing initializer in const declaration.


x = 5;
console.log(x)
Run Cod

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

A function is a block of code that performs a specific task.

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

• a function to color the circle

Dividing a complex problem into smaller chunks makes your program easy to
understand and reusable.

JavaScript also has a huge number of inbuilt functions. For


example, Math.sqrt() is a function to calculate the square root of a number.
In this tutorial, you will learn about user-defined functions.

Declaring a Function

The syntax to declare a function is:

function nameOfFunction () {
// function body
}

• A function is declared using the function keyword.


• The basic rules of naming a function are similar to naming a variable. It is
better to write a descriptive name for your function. For example, if a function
is used to add two numbers, you could name the function add or addNumbers .

• The body of function is written within {} .

For example,

// declaring a function named greet()


function greet() {
console.log("Hello there");
}

Calling a Function

In the above program, we have declared a function named greet() . To use


that function, we need to call it.
Here's how you can call the above greet() function.

// function call
greet();

Function Parameters

A function can also be declared with parameters. A parameter is a value that


is passed when declaring a function.
Add Two Numbers
// program to add two numbers using a function
// declaring a function
function add(a, b) {
console.log(a + b);
}

// 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 Javascript, functions can also be defined as expressions. For example,

// program to find the square of a number


// function is declared inside the variable
let x = function (num) { return num * num };
console.log(x(4));

// can be used as variable value for other variables


let y = x(3);
console.log(y);

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.

JavaScript Variable Scope

Scope refers to the availability of variables and functions in certain parts of the
code.

In JavaScript, a variable has two types of scope:

1. Global Scope
2. Local Scope

3. A variable declared at the top of a program or outside of a function is


considered a global scope variable.
4. Let's see an example of a global scope variable.
5. // program to print a text
6. let a = "hello";
7.
8. function greet () {
9. console.log(a);
10. }
11.
12. greet(); // hello

In the above program, variable a is declared at the top of a program and is a


global variable. It means the variable a can be used anywhere in the program.
The value of a global variable can be changed inside a function. For example,

// program to show the change in global variable


let a = "hello";

function greet() {
a = 3;
}

// before the function call


console.log(a);

//after the function call


greet();
console.log(a); // 3

the above program, variable a is a global variable. The value of a is hello .

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.

In JavaScript, a variable can also be used without declaring it. If a variable is


used without declaring it, that variable automatically becomes a global
variable.

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.

Local Scope Variable


// program showing local scope of a variable
let a = "hello";

function greet() {
let b = "World"
console.log(a + b);
}

greet();
console.log(a + b); // error

In the above program, variable a is a global variable and variable b is a local


variable. The variable b can be accessed only inside the function greet .
Hence, when we try to access variable b outside of the function, an error
occurs.

let is Block Scoped

The let keyword is block-scoped (variable can be accessed only in the immediate
block).

Example: block-scoped Variable


// program showing block-scoped concept
// global variable
let a = 'Hello';

function greet() {

// local variable
let b = 'World';

console.log(a + ' ' + b);

if (b == 'World') {

// block-scoped variable
let c = 'hello';

console.log(a + ' ' + b + ' ' + c);


}

// variable c cannot be accessed here


console.log(a + ' ' + b + ' ' + c);
}
greet();

In the above program, variable

• a is a global variable. It can be accessed anywhere in the program.


• b is a local variable. It can be accessed only inside the function greet .

• c is a block-scoped variable. It can be accessed only inside the if statement


block.
Hence, in the above program, the first two console.log() work without any
issue.
However, we are trying to access the block-scoped variable c outside of the
block in the third console.log() . This will throw an error.

JavaScript Arrow Function

Arrow function is one of the features introduced in the ES6 version of


JavaScript. It allows you to create functions in a cleaner way compared to
regular functions. For example,

This function

// function expression
let x = function(x, y) {
return x * y;
}

can be written as

// using arrow functions


let x = (x, y) => x * y;

using an arrow function.


Arrow Function Syntax

The syntax of the arrow function is:

let myFunction = (arg1, arg2, ...argN) => {


statement(s)
}

Here,

• myFunction is the name of the function


• arg1, arg2, ...argN are the function arguments
• statement(s) is the function body
If the body has single statement or expression, you can write arrow function
as:

let myFunction = (arg1, arg2, ...argN) => expression

Arrow Function with No Argument

If a function doesn't take any argument, then you should use empty
parentheses. For example,

let greet = () => console.log('Hello');


greet(); // Hello
Arrow Function with One Argument

If a function has only one argument, you can omit the parentheses. For
example,

let greet = x => console.log(x);


greet('Hello'); // Hello

Arrow Function as an Expression

You can also dynamically create a function and use it as an expression. For
example,
let age = 5;

let welcome = (age < 18) ?


() => console.log('Child') :
() => console.log('Ages');

welcome(); // Child

Multiline Arrow Functions

If a function body has multiple statements, you need to put them inside curly
brackets {} . For example,

let sum = (a, b) => {


let result = a + b;
return result;
}

let result1 = sum(5,7);


console.log(result1); // 12
JavaScript Default Parameters

The concept of default parameters is a new feature introduced in


the ES6 version of JavaScript. This allows us to give default values to function
parameters. Let's take an example,
function sum(x = 3, y = 5) {

// 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

It is also possible to provide expressions as default values.

Passing Parameter as Default Values


function sum(x = 1, y = x, z = x + y) {
console.log( x + y + z );
}

sum(); // 4

In the above program,

• The default value of x is 1


• The default value of y is set to x parameter
• The default value of z is the sum of x and y

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();

Passing Function Value as Default Value


// using a function in default value expression

const sum = () => 15;

const calculate = function( x, y = x * sum() ) {


return x + y;
}

const result = calculate(10);


console.log(result); // 160

In the above program,

• 10 is passed to the calculate() function.


• x becomes 10 , and y becomes 150 (the sum function returns 15 ).

• The result will be 160 .


JavaScript Objects

JavaScript object is a non-primitive data-type that allows you to store multiple


collections of data.
Here is an example of a JavaScript object.

// 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
}

Here, an object object_name is defined. Each member of an object is a key:


value pair separated by commas and enclosed in curly braces {} .

For example,

// object creation
const person = {
name: 'Hassan',
age: 20
};
console.log(typeof person); // object
JavaScript Object Properties

In JavaScript, "key: value" pairs are called properties. For example,

let person = {
name: 'Ali',
age: 20
};

Here, name: 'Ali' and age: 20 are properties.

Accessing Object Properties

You can access the value of a property by using its key.


1. Using dot Notation
Here's the syntax of the dot notation.

objectName.key

For example,

const person = {
name: 'khan',
age: 20,
};

// accessing property
console.log(person.name); // khan
2. Using bracket Notation

Here is the syntax of the bracket notation.

objectName["propertyName"]

For example,

const person = {
name: 'khan',
age: 20,
};

// accessing property
console.log(person["name"]); // khan

JavaScript Nested Objects

An object can also contain another object. For example,

// nested object
const student = {
name: 'ali',
age: 20,
marks: {
science: 70,
math: 75
}
}

// accessing property of student object


console.log(student.marks); // {science: 70, math: 75}

// accessing property of marks object


console.log(student.marks.science); // 70
JavaScript Object Methods

In JavaScript, an object can also contain a function. For example,

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,

const words = ['hello', 'world', 'welcome'];

Here, words is an array. The array is storing 3 values.

Create an Array

You can create an array using two ways:

1. Using an array literal

The easiest way to create an array is by using an array literal [] . For example,

const array1 = ["eat", "sleep"];


2. Using the new keyword

You can also create an array using JavaScript's new keyword.

const array2 = new Array("eat", "sleep");

Here are more examples of arrays:

// empty array
const myList = [ ];

// array of numbers
const numberArray = [ 2, 4, 6, 8];

// array of strings
const stringArray = [ 'eat', 'work', 'sleep'];

// array with mixed data types


const newData = ['work', 'exercise', 1, true];

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')}
];

Access Elements of an Array

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"

Add an Element to an Array

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'];

// add an element at the end


dailyActivities.push('exercise');

console.log(dailyActivities); // ['eat', 'sleep', 'exercise']

The unshift() method adds an element at the beginning of the array. For
example,
let dailyActivities = ['eat', 'sleep'];

//add an element at the start


dailyActivities.unshift('work');

console.log(dailyActivities); // ['work', 'eat', 'sleep']

Change the Elements of an Array

You can also add elements or change the elements by accessing the index
value.

let dailyActivities = [ 'eat', 'sleep'];

// this will add the new element 'exercise' at the 2 index


dailyActivities[2] = 'exercise';

console.log(dailyActivities); // ['eat', 'sleep', 'exercise']


Remove an Element from an Array

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'];

// remove the last element


dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']

// remove the last element from ['work', 'eat', 'sleep']


const removedElement = dailyActivities.pop();

//get removed element


console.log(removedElement); // 'sleep'
console.log(dailyActivities); // ['work', 'eat']

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'];

// remove the first element


dailyActivities.shift();

console.log(dailyActivities); // ['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,

const dailyActivities = [ 'eat', 'sleep'];

// this gives the total number of elements in an array


console.log(dailyActivities.length); // 2
Array Methods

In JavaScript, there are various array methods available that makes it easier
to perform useful calculations.

Some of the commonly used JavaScript array methods are:

Method Description

concat() joins two or more arrays and returns a result

indexOf() searches an element of an array and returns its position

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

forEach() calls a function for each element

includes() checks if an array contains a specified element

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

sort() sorts the elements alphabetically in strings and in ascending order

slice() selects the part of an array and returns the new array

splice() removes or replaces existing elements and/or adds new elements

JavaScript Array Methods


let dailyActivities = ['sleep', 'work', 'exercise']
let newRoutine = ['eat'];

// sorting elements in the alphabetical order


dailyActivities.sort();
console.log(dailyActivities); // ['exercise', 'sleep', 'work']

//finding the index position of string


const position = dailyActivities.indexOf('work');
console.log(position); // 2

// slicing the array elements


const newDailyActivities = dailyActivities.slice(1);
console.log(newDailyActivities); // [ 'sleep', 'work']

// concatenating two arrays


const routine = dailyActivities.concat(newRoutine);
console.log(routine); // ["exercise", "sleep", "work", "eat"]

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

The syntax of the forEach() method is:

array.forEach(function(currentValue, index, arr))

Here,

• function(currentValue, index, arr) - a function to be run for each element of an


array

• currentValue - the value of an array

• index (optional) - the index of the current element

arr (optional) - the array of the current elements

forEach with Arrays

The forEach() method is used to iterate over an array. For example,

let students = ['ali', 'hassan', 'saeed'];

// using forEach
students.forEach(myFunction);

function myFunction(item) {

console.log(item);
}

Output

ali
hassan
saeed
Updating the Array Elements

As we have seen in the above example, the forEach() method is used to


iterate over an array, it is quite simple to update the array elements. For
example,
let students = ['ali', 'hassan', 'saeed'];

// using forEach
students.forEach(myFunction);

function myFunction(item, index, arr) {

// adding strings to the array elements


arr[index] = 'Hello ' + item;
}

console.log(students);

Output

["Hello ali", "Hello hassan", "Hello saeed"]

forEach with Arrow Function

You can use the arrow function with the forEach() method to write a program.
For example,
// with arrow function and callback

const students = ['ali', 'hassan', 'saeed'];

students.forEach(element => {
console.log(element);
});

students.forEach((item, index, arr)=> {


console.log("hello"+item);
});
JavaScript for...in loop

The syntax of the for...in loop is:

for (key in object) {


// body of for...in
}

In each iteration of the loop, a key is assigned to the key variable. The loop
continues for all object properties.

Iterate Through an Object


const student = {
name: 'khadija',
class: 7,
age: 12
}

// using for...in
for ( let key in student ) {

// display the properties


console.log(`${key} => ${student[key]}`);
}
WEEK #2

Essential JavaScript for React Part 2


1. Template literals
2. Spread and Rest Operators
3. Destructuring
4. JavaScript Map, Reduce, and Filter
5. Ternary Operators
6. ES Modules and Import / Export Syntax

JavaScript Template Literals

Template literals (template strings) allow you to use strings or embedded


expressions in the form of a string. They are enclosed in backticks `` . For
example,

const name = 'Ali';


console.log(`Hello ${name}!`); // Hello Ali!

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

The spread operator ... is used to expand or spread an iterable or an array.


For example,
const arrValue = ['My', 'name', 'is', 'Ali'];

console.log(arrValue); // ["My", "name", "is", "Ali"]


console.log(...arrValue); // My name is Ali

Copy Array Using 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"]

Clone Array Using Spread Operator

In JavaScript, objects are assigned by reference and not by values. For


example,

let arr1 = [ 1, 2, 3];


let arr2 = arr1;

console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 2, 3]

// append an item to the array


arr1.push(4);

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,

let arr1 = [ 1, 2, 3];

// copy using spread syntax


let arr2 = [...arr1];

console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 2, 3]

// append an item to the array


arr1.push(4);

console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 3]

Spread Operator with Object

You can also use the spread operator with object literals. For example,

const obj1 = { x : 1, y : 2 };
const obj2 = { z : 3 };

// add members obj1 and obj2 to obj3


const obj3 = {...obj1, ...obj2};

console.log(obj3); // {x: 1, y: 2, z: 3}
Rest Parameter

When the spread operator is used as a parameter, it is known as the rest


parameter.

You can also accept multiple arguments in a function call using the rest
parameter. For example,

let func = function(...args) {


console.log(args);
}

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,

function sum(x, y ,z) {


console.log(x + y + z);
}

const num1 = [1, 3, 4, 5];

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'
}

let name = person.name;


let age = person.age;
let gender = person.gender;

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, you could write the above program as:

let { age, gender, name } = person;


console.log(name); // khadija

For example,

let {name1, age, gender} = person;


console.log(name1); // undefined

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

Access Object Keys, Values & Entries


You often need to look through the properties and values of plain JavaScript
objects.
Here are the common lists to extract from an object:
• The keys of an object is the list of property names.
• The values of an object is the list of property values.
• The entries of an object is the list of pairs of property names and
corresponding values.
Let's consider the following JavaScript object:
const person = {
name: 'Hassan',
city: 'Rawalpindi'
};

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.

Let's use Object.keys() to get the keys of person 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.

Let's use this function to get the values of hero object:


const person = {
name: 'Hassan',
city: 'Rawalpindi'
};
Object.values(person); // => ['Hassan', 'Rawalpindi']

Object.values(person) returns the values of hero: ['Hassan', Rawalpindi'].

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']]

Object.entries(person) returns the entries of person: [['name', 'Hassan'], ['city',


'Rawalpindi']].

Array Destructuring

You can also perform array destructuring in a similar way. For example,

const arrValue = ['one', 'two', 'three'];

// destructuring assignment in arrays


const [x, y, z] = arrValue;

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,

let arrValue = [10];

// assigning default value 5 and 7


let [x = 5, y = 7] = arrValue;

console.log(x); // 10
console.log(y); // 7

In the above program, arrValue has only one element. Hence,


• the x variable will be 10
• the y variable takes the default value 7
In object destructuring, you can pass default values in a similar way. For
example,

const person = {
name: 'Ali',
}

// assign default value 26 to age if undefined


const { name, age = 26} = person;

console.log(name); // Ali
console.log(age); // 26

Swapping Variables

In this example, two variables are swapped using the destructuring


assignment syntax.
// program to swap 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,

const arrValue = ['one', 'two', 'three'];

// destructuring assignment in arrays


const [x, , z] = arrValue;

console.log(x); // one
console.log(z); // three
Run Co

In the above program, the second element is omitted by using the comma
separator , .

Assign Remaining Elements to a Single Variable

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,

const arrValue = ['one', 'two', 'three', 'four'];

// throws an error
const [ ...x, y] = arrValue;

console.log(x); // error

JavaScript Map, Reduce, and Filter - JS Array Functions


Map, reduce, and filter are all array methods in JavaScript. Each one will
iterate over an array and perform a transformation or computation. Each will
return a new array based on the result of the function.

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.

const numbers = [1, 2, 3, 4];


const doubled = numbers.map(item => item * 2);
console.log(doubled); // [2, 4, 6, 8]

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.

const numbers = [1, 2, 3, 4];


const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]

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 }
];

const studentGrades = students.filter(student => student.grade >= 90);


return studentGrades; // [ { name: 'ali', grade: 96 }, { name: 'nasir', grade: 100
}, { name: 'anas', grade: 90 } ]
Reduce
The reduce() method reduces an array of values down to just one value. To
get the output value, it runs a reducer function on each element of the array.

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.

const numbers = [1, 2, 3, 4];


const sum = numbers.reduce(function (result, item) {
return result + item;
}, 0);
console.log(sum); // 10
In the next example, reduce() is used to transform an array of strings into a
single object that shows how many times each string appears in the array.
Notice this call to reduce passes an empty object {} as
the initialValue parameter. This will be used as the initial value of the
accumulator (the first argument) passed to the callback function.

var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];


var petCounts = pets.reduce(function(obj, pet){
if (!obj[pet]) {
obj[pet] = 1;
} else {
obj[pet]++;
}
return obj;
}, {});

console.log(petCounts);

/*
Output:
{
dog: 2,
chicken: 3,
cat: 1,
rabbit: 1
}
*/

Ternary Operator

A ternary operator evaluates a condition and executes a block of code based


on the condition.

Its syntax is:

condition ? expression1 : expression2

The ternary operator evaluates the test condition.

• If the condition is true , expression1 is executed.


• If the condition is false , expression2 is executed.
The ternary operator takes three operands, hence, the name ternary operator.
It is also known as a conditional operator.
Let's write a program to determine if a student passed or failed in the exam
based on marks obtained.

Example: JavaScript Ternary Operator


// program to check pass or fail

let marks = 78;

// check the condition


let result = (marks >= 40) ? 'pass' : 'fail';

console.log(`You ${result} the exam.`);

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,

Suppose, a file named Hello.js contains the following code:

// 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';

// using greetPerson() defined in greet.js


let displayName = sayHello('Yasir');

console.log(displayName); // Hello Yasir

Here,

• The sayHi() function in the Hello.js is exported using the export keyword

export function sayHello(name) {



}

• Then, we imported sayHi() in another file using the import keyword. To import
functions, objects, etc., you need to wrap them around { }.

import { sayHi } from './Hello.js';

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:

export const myNumbers = [1, 2, 3, 4];

const animals = ['Panda', 'Bear', 'Eagle']; // Not available directly


outside the module

export function myLogger() {


console.log(myNumbers, animals);
}
Or you can export desired members in a single statement at the end of the
module:
export { myNumbers, myLogger};

Exporting with alias


You can also give an aliases to exported members with the as keyword:
export { myNumbers, myLogger as Logger}

Default export
You can define a default export with the default keyword:
export const myNumbers = [1, 2, 3, 4];
const animals = ['Panda', 'Bear', 'Eagle'];

export default function myLogger() {


console.log(myNumbers, pets);
}

Importing with alias


You can also alias members at import time:
import myLogger as Logger from 'app.js';

Importing all exported members


You can import everything that’s imported by a module like this:
import * as Utils from 'app.js';
This allows you access to members with the dot notation:
Utils.myLogger();
WEEK #3

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

There is no need to know the languages used for platform-specific application


development, as React Native uses only JavaScript, probably the most
popular programming language right now, for the development of mobile
applications.

• Performance

React Native enables speedy development of mobile applications since a similar


code is used for applications for both platforms. It also facilitates a hot reloading
feature that makes sure that small changes done to the application are
immediately visible to the developer.

• Large Developers’ Community

A huge developers’ community ensures that all the queries are resolved in time,
and therefore, adequate support is available for the React Native framework.

• It Keeps Getting Better

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

Though the framework is relatively new, many companies have already


migrated the applications to this framework. Additional companies are looking
to use the framework to speed up the process of development and maintenance.

• Excellent Career Opportunities

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/

Consider this variable declaration:

const element = <Text>Hello, world!</Text>;

This funny tag syntax is neither a string nor HTML.


It is called JSX, and it is a syntax extension to JavaScript. We recommend using it
with React to describe what the UI should look like. JSX may remind you of a
template language, but it comes with the full power of JavaScript.
JSX produces React “elements”. Below, you can find the basics of JSX necessary
to get you started.

Embedding Expressions in JSX


In the example below, we declare a variable called name and then use it inside JSX
by wrapping it in curly braces:
const name = 'ali khan';const element = <Text>Hello,
{name}</Text>;
You can put any valid JavaScript expression inside the curly braces in JSX. For
example, 2 + 2, user.firstName, or formatName(user) are all valid JavaScript
expressions.
In the example below, we embed the result of calling a JavaScript
function, formatName(user), into an <h1> element.
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}

const user = {
firstName: 'Harper',
lastName: 'Perez'
};

const element = (
<Text>
Hello, {formatName(user)}! </Text>
);

JSX is an Expression Too


After compilation, JSX expressions become regular JavaScript function calls and
evaluate to JavaScript objects.
This means that you can use JSX inside of if statements and for loops, assign it to
variables, accept it as arguments, and return it from functions:
function getGreeting(user) {
if (user) {
return <Text>Hello, {formatName(user)}!</Text>; }
return <Text>Hello, Stranger.</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.

The simplest way to define a component is to write a JavaScript function:


function Welcome(props) {
return <Text>Hello, {props.name}</Text>;
}

This function is a valid React component because it accepts a single “props”


(which stands for properties) object argument with data and returns a React
element. We call such components “function components” because they are
literally JavaScript functions.

Text and View Components


As you can guess, <Text></Text> is a wrapper for any text in your page. This
component is similar to a <p> tag in HTML. Now, similar to a <div> </div> tag,
you would wrap your <Text> </Text> in a <View> </View>. That’s
right, <View> acts very similar to <div>, and the basic idea is that it is a container
perfect for dividing up and styling your page.

Here is the basic set up of a React Native page:

import React from "react";


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

export default function App{


render() {
return (
<View style={{
flex: 1,
justifyContent: "center",
alignItems: "center"
}} >
<Text> Hello World! </Text>
</View>
);
}
}

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.

The following style is justifyContent: "center". This aligns children of a container


in the center of the container's main axis. Finally, we have alignItems: "center",
which aligns children of a container in the center of the container's cross axis.
The other unusual thing in this code example is <View style= {{ …..}}><Text>Hello
world!</Text></View>. This is JSX - a syntax for embedding XML within
JavaScript. Many frameworks use a specialized templating language which lets
you embed code inside markup language. In React, this is reversed. JSX lets you
write your markup language inside code. It looks like HTML on the web, except
instead of web things like <div> or <span>, you use React components. In this
case, <Text> is a Core Component that displays some text and View is like
the <div> or <span>.
Speaking of the <Text> component, you can wrap another component inside it like
this:

<Text style={{ fontSize: 24 }}>Here is the first text </Text>


<Text style={{<Text style={{ color: red }}>
fontSize: 14 }}>And the second text.</Text>
</Text>

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:

const WelcomeMessage = (props) => {


return (
<View style={styles.center}>
<Text>Hi {props.name}!</Text>
</View>
);
}

const LotsOfWelcomeMessages = () => {


return (
<View style={[styles.center, {top: 50}]}>
<WelcomeMessage name='Hassan' />
<WelcomeMessage name='Saeed' />
<WelcomeMessage name='Ali' />
</View>
);

Using name as a prop lets us customize the WelcomeMessage component, so we can


reuse that component for each of our greetings. This example also uses
the WelcomeMessage component in JSX. The power to do this is what makes react so
cool.

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';

const styles = StyleSheet.create({


center: {
alignItems: 'center'
}
})

// React Native Counter Example using Hooks!

import React, { useState } from 'react';


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

const App = () => {


const [count, setCount] = useState(0);

return (
<View style={styles.container}>
<Text>You clicked {count} times</Text>
<Button
onPress={() => setCount(count + 1)}
title="Click me!"
/>
</View>
);
};

// React Native Styles


const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});

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.

const Message= () => {


const [message, setMessage]= useState( '' );
<View>
<Text> message</Text>
<Button
onPress={() => setMessage('Hi')}
title="SayHi!"
/>

<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.

Stylesheet Create Method


The Stylesheet.create function in React Native is used to create a StyleSheet style
reference from the specified object. Always use StyleSheet.create() when you can.
It validates the styles and making a stylesheet from a style object makes it possible
to refer to it by ID instead of creating a new style object every time.

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.

To read more about visit following links:

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

Handling Text Input


TextInput is a Core Component that allows the user to enter text. It has
an onChangeText prop that takes a function to be called every time the text
changed, and an onSubmitEditing prop that takes a function to be called when the
text is submitted.

import React, { useState } from 'react';


import { Text, TextInput, View } from 'react-native';
const TextInputDemo= () => {
const [text, setText] = useState('');
return (
<View style={{padding: 10}}>
<TextInput
style={{height: 40}}
placeholder="Type here !"
onChangeText={newText => setText(newText)}
defaultValue={text}
/>
<Text style={{padding: 10, fontSize: 42}}>
You Entered: {text}
</Text>
</View>
);
}
export default TextInputDemo;
Radio Button
Radio buttons are an essential element of forms. They are used when there is a list
of two or more options that are mutually exclusive and you can choose only option.
React Native Paper is a collection of customizable and production-ready
components for React Native, following Google’s Material Design guidelines. We
will use Radio button and Check box components developed by React Native
Paper. To install React Native package run following command
npm install react-native-paper@5.0.0-rc.6

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'

const App = () => {


const [gender, setGender] = React.useState('male');
const [maritalStatus, setMaritalStatus] = React.useState('single');
return (
<View>
<Text>Choose Gender:</Text>
<RadioButton.Group onValueChange={value => setGender(value)}
value={gender}>
<RadioButton.Item label="Male" value="male" />
<RadioButton.Item label="Female" value="female" />
</RadioButton.Group>
<Text>Choose Status:</Text>
<RadioButton.Group onValueChange={value =>
setMaritalStatus(value)} value={maritalStatus}>
<RadioButton.Item label="Single" value="single" />
<RadioButton.Item label="Married" value="married" />
</RadioButton.Group>
<Text>Your gender is : {gender} and You are {maritalStatus}</Text>
</View>
);
};

export default App;


Checkbox

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.

First, install the @react-native-community/checkbox package by running this


command:

npm install @react-native-community/checkbox

For information about React Native checkbox properties visit following link

https://github.com/react-native-checkbox/react-native-checkbox

Here’s the code for the React Native checkbox example:

import React, {Component} from 'react';


import {StyleSheet, Text, View, Button} from 'react-native';
import CheckBox from '@react-native-community/checkbox';
const initialState = {
react: false,
next: false,
vue: false,
angular: false,
};
export default function App() {
const [state, setState] = React.useState(initialState);
const [toggleButton, setToggleButton] =
React.useState(false);
return (
<View style={styles.container}>
<View>
<View>
<View style={styles.checkboxWrapper}>
<CheckBox
value={state.react}
onValueChange={
value =>
//better approach
//to update state
setState(
prevState => ({
...prevState,react:value

}))}
/>
<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,
},
});

Building React Native Picker


The React Native picker component is the equivalent of a dropdown in regular
JavaScript. It is basically used to render a list of multiple choices where users then
select only one option from the list. The functionality comes in handy when you have
to ask a question with varying answers.

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:

import React, {useState} from 'react';


import {Text, StyleSheet, View, TextInput, Button} from 'react-
native';
import { Picker } from '@react-native-picker/picker';

const App = () => {


const [currency, setCurrency] = useState('US Dollar');
return (
<View >
<Text > Demo Form </Text>
<View>
<TextInput
placeholder="Email" />
<TextInput
secureTextEntry={true}
placeholder="Password"
/>
<Picker
selectedValue={currency}
onValueChange={currentCurrency =>
setCurrency(currentCurrency)}>
<Picker.Item label="USD" value="US Dollars" />
<Picker.Item label="PKR" value="Pakistani Rupee" />
<Picker.Item label="BDT" value="Bangladeshi Taka" />
</Picker>
<Text>
Selected: {currency}
</Text>
</View>
</View>
);
};
const styles = StyleSheet.create({
//Check project repo for styles
});

export default App;


WEEK #5
1. Touchable Opacity
2. Pressable
3. Scroll View
4. FlatList
5. SectionList
6. RefreshControl

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

import React, { useState } from 'react';


import { TouchableOpacity, Text, View, StyleSheet } from 'react-native';
const App = () => {
const [count, setCount] = useState(0);
const incrementCount = () => setCount(count + 1);
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={incrementCount}>
<Text> Touch Here </Text>
</TouchableOpacity>
<View style={styles.countContainer}>
<Text style={styles.countText}>{count !== 0 ? count : null}</Text>
</View>
</View>
);
};

export default App;

const styles = StyleSheet.create({


container: {
flex: 1,
justifyContent: 'center',
paddingHorizontal: 10,
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
},
countContainer: {
alignItems: 'center',
padding: 10,
},
countText: {
color: '#FF00FF',
},
});
The output for the above code is:

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

<Pressable onPress={ //callback function}>

<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

import React from 'react';


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

const App = () => {


const onPressFunction = () =>{
console.log('PRESSED!')
}
return (
<View style={styles.container}>
<Pressable onPress={onPressFunction}>
<View style={styles.button}>
<Text style={styles.text}>I am pressable!</Text>
</View>
</Pressable>
</View>
);
};
export default App

const styles = StyleSheet.create({


container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
button: {
backgroundColor: '#F0FF42',
padding: 10,
borderRadius: 8
},
text: {
textAlign: 'center',
fontSize: 20,
}
});

The output for the above code is:


Why Should We Use It Instead of Touchable

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

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

const App = () => {


return (
<View style={styles.container}>
<ScrollView style={styles.scrollView}>
<Text style={styles.text}>
For a long time, React Native was considered to be commercially
unviable. It wasn’t developed or supported enough to produce “native-like” apps.
But the times have changed. React Native is gaining popularity, gaining community
support, and gaining more market share. It’s getting easier and easier to write
brilliant apps using React Native—and the world is taking notice.
</Text>
</ScrollView>
</View>
);
};

export default App;


const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 20,
},
scrollView: {
backgroundColor: ' #FD841F',

marginHorizontal: 20,
},
text: {
fontSize: 42,
},
});

The output for the above code is


FlatList
Flatlist is the easiest way to render a scrollable list of items. We just have to pass
the data (as an array) without any formatting to it and it will render the items.
Flatlist works efficiently with large data as it renders only those items that are
displaying on the screen, and not all the items at once.

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';

const App = () => {


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={({item}) => (

<View style={styles.item}>
<Text style={styles.text}>{item.name}</Text>
</View>
)}
/>
</View>
);
};

export default App;

const styles = StyleSheet.create({


container: {
flex: 1,
margin: 30,
},
item: {
backgroundColor: '#FF5858',
padding: 20,
marginBottom: 50,
borderRadius: 12
},
text: {
fontSize: 24,
textAlign: 'center',
color: 'white',
},
});

The output for the above code is:

A better approach would be to create a callback function for the renderItem prop
like this

const App = () => {


let data = [
{ id: 1, name: 'Hassan' },
{ id: 2, name: 'Saeed' },
{ id: 3, name: 'Irfan' },
{ id: 4, name: 'Ali' },
{ id: 5, name: 'Hassan' },
{ id: 6, name: 'Saeed' },
{ id: 7, name: 'Irfan' },
{ id: 8, name: 'Ali' },
];
const Item = ({ item }) => {
return (
<View style={styles.item}>
<Text style={styles.text}>{item.name}</Text>
</View>
);
};
return (
<View style={styles.container}>
<FlatList
data={data}
keyExtractor={(item) => item.id}
renderItem={Item}
/>
</View>
);
};

export default App;

Styles will remain the same for the above code example

To read more about FlatList, visit following links:

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"]
}
];

const Item = ({ title }) => (


<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);

const Header = ({title}) => (


<Text style={styles.header}>{title}</Text>
)

const App = () => (


<View style={styles.container}>
<SectionList
sections={data}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader = {({section}) => <Header title={section.title}/>}
/>
</View>
);

const styles = StyleSheet.create({


container: {
flex: 1,
marginTop: 20,
marginHorizontal: 16
},
item: {
backgroundColor: "#FF5858",
borderRadius: 8,
padding: 20,
marginVertical: 8
},
header: {
fontSize: 32,
},
title: {
fontSize: 24,
color: 'white',
textAlign: 'center'
}
});

export default App;

The output for the above code is:

To read more about SectionList, visit following links:

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);

const onRefresh = () => {


setRefreshing(true);
setTimeout(() => {
setRefreshing(false);
}, 2000);
};

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' },
];

const ShowItem = ({ item }) => {


return (
<View style={styles.item}>
<Text style={styles.text}>{item.name}</Text>
</View>
);
};

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',
},
});

export default App;

The output for the above code is:


To read more about Refresh Control, visit following links:

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

Intro to useEffect Hook


React useEffect is a function that gets executed for 3 different React component
lifecycles. Those lifecycles are

a. Component Did Mount


b. Component Did Update
c. Component Will Unmount

Syntax

import React, {useEffect} from 'react';


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

const App = () => {


// it accepts two arguments:
// a function
// an array (optional)
useEffect(() => {}, []);
return (
<View>
<Text>
useEffect Hook
</Text>
</View>
);
}

export default App


The function passed to useEffect is a callback function. This will be called after the
component renders.

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

import React, { useEffect, useState } from 'react';


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

const App = () => {


const [count, setCount] = useState(0);

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.

import React, { useEffect, useState } from 'react';


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

const App = () => {


const [count, setCount] = useState(0);
const [squareCount, setSquareCount] = useState(0);

useEffect(() => {
setSquareCount(count * count);
}, [count]);

const incrementCount = () => {


setCount(count + 1);
};

return (
<View>
<Text>Count: {count}</Text>
<Text>Square: {squareCount}</Text>
<Button title="Increment" onPress={incrementCount} />
</View>
);
};

export default App;


In the above example I added count state in the dependency array, which means the
callback function will run when the value of count changes.

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

SQLite is a software library that provides a relational database management


system. The lite in SQLite means lightweight in terms of setup, database
administration, and required resources.

Installation of SQLite
To install SQLite, run the following command in terminal:

npm install --save react-native-sqlite-storage

SQLite Basic Queries


To create a table, we can use the following query
CREATE TABLE Users(id INTEGER PRIMARY KEY, name VARCHAR(30),
city VARCHAR(25))

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

How to use SQLite?


You just have to import the library like this:
import { openDatabase } from 'react-native-sqlite-storage';

and open the database using


const db = openDatabase({ name: 'DatabaseName.db' });

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
);
});

SQLite CRUD App


import react, { useEffect, useState } from 'react';
import {
View,
Text,
FlatList,
TextInput,
StyleSheet,
Button,
Alert,
TouchableOpacity,
} from 'react-native';
import { openDatabase } from 'react-native-sqlite-storage';

const db = openDatabase({ name: 'wishListDB' });

//public static void main(String args[]/** cmd line */)


export default function App() {
useEffect(() => {
createTable();
fetchWishList();
}, []);
const [wishlist, setWishList] = useState([]);
const [name, setName] = useState('');
const [wishid, setWishId] = useState(0);
const [buttonTitle, setButtonTitle] = useState('Add Wish');

const createTable = () => {


db.transaction((txn) => {
txn.executeSql(
`create Table if not Exists wishlist (id INTEGER PRIMARY KEY
AUTOINCREMENT,name varchar(20))`,
[],
(sqltxn, res) => {
console.log('Wishlist Table created Successfully..');
},
(error) => {
console, log('Error occured during Table Creation...');
}
);
});
};
function fetchWishList() {
console.log('Fetch Wish List Execution Started');
db.transaction((txn) => {
txn.executeSql(
`Select * from wishlist order by id desc`,
[],
(sqltxn, res) => {
let len = res.rows.length;
let resultSet = [];
for (let i = 0; i < len; i++) {
let record = res.rows.item(i);
resultSet.push({ id: record.id, name: record.name });
}
setWishList(resultSet);
},
(error) => {
console, log('Error occured during Fetching WishList...');
}
);
});
}

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>
);
}

const myStyles = StyleSheet.create({


container: {
flex: 1,
padding: 10,
margin: 10,
backgroundColor: '#cddf',
},
input: {
borderStyle: 'solid',
borderRadius: 20,
borderColor: '#eeccff',
height: 60,
backgroundColor: '#ddcc22',
marginBottom: 5,
},
button: {
width: 70,
backgroundColor: 'blue',
color: '#fff',
borderRadius: 30,
textAlign: 'center',
},
});

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.

Installation of React Navigation


To install react navigation, run the following commands:
npm install @react-navigation/native
npm install react-native-screens react-native-safe-area-context

Working with Stack Navigation


Stack navigation provides a way for react-native apps to transition between screens
by using a stack, which means the screens are stacked on each other.

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";

import Home from "../screens/Home";


import About from "../screens/About";

const Stack = createStackNavigator();


const App = () => {
return (
<Stack.Navigator initialRouteName='Home'>
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="About" component={About} />
</Stack.Navigator>
);
}

export default App

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.

Passing parameters to routes

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


import React from 'react';

const Home = ({navigation}) => {


const onPressHandler = () => {
navigation.navigate('About', {
name: 'Amjad',
city: 'rwp',
status: 'self-employed',
});
};
return (
<View>
<Text>Home</Text>
<Button onPress={onPressHandler} title="Move to About
Screen" />
</View>
);
};
export default Home;

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

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


import React from 'react';

const About = ({route, navigation}) => {


const {name, status} = route.params;
const onPressHandler = () => {
navigation.navigate('Home');
};
return (
<View>
<Text>{name}</Text>
<Text>{status}</Text>
<Button onPress={onPressHandler} title="Move to Home
Screen" />
</View>
);
};

export default About;

Working with Tab Navigation


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).
To create tab navigation, install the required library by running the following
command
npm install @react-navigation/bottom-tabs

import React from 'react';


import {StyleSheet, Text, View} from 'react-native';
import {NavigationContainer} from '@react-
navigation/native';
import {createBottomTabNavigator} from '@react-
navigation/bottom-tabs';

const HomeScreen = () => {


return (
<View>
<Text>Home Screen</Text>
</View>
);
};
const AboutScreen = () => {
return (
<View>
<Text>About Screen</Text>
</View>
);
};

const Tab = createBottomTabNavigator();

const App = () => {


return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="About" component={AboutScreen} />
</Tab.Navigator>
</NavigationContainer>
);
};

export default App;


const styles = StyleSheet.create({});

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

import React from 'react';


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

const handleAlert = () => {


Alert.alert('Status', 'Successful, letting you in...', [
{
text: 'OK',
onPress: () => console.log('OK Button Pressed'),
},
]);
};

const App = () => {


return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={handleAlert}>
<Text style={styles.text}>Press Me</Text>
</TouchableOpacity>
</View>
);
};

export default App;

const styles = StyleSheet.create({


container: {
flex: 1,
paddingTop: 20,
paddingHorizontal: 10,
alignItems: 'center',
justifyContent: 'center'
},
button: {
backgroundColor: '#B01E68',
paddingVertical: 20,
borderRadius: 10,
width: '50%'
},
text: {
textAlign: 'center',
color: 'white',
fontWeight: 'bold',
textTransform: 'uppercase'
}
});

How to create an alert with two options


For two options alert, the only change will be

Alert.alert('Status', 'Successful, letting you in...', [


{
text: 'OK',
// this fucntion down here 👇 gets called everytime the OK Button is
pressed
onPress: () => console.log('OK Button Pressed'),
},
{
text: 'Cancel',
// this fucntion down here 👇 gets called everytime the Cancel Button is
pressed
onPress: () => console.log('Cancel Button Pressed'),
},
]);

How to create an alert with three options


For three options alert, the only change will be

Alert.alert('Status', 'Successful, letting you in...', [


{
text: 'OK',
// this fucntion down here 👇 gets called everytime the OK Button is
pressed
onPress: () => console.log('OK Button Pressed'),
},
{
text: 'Cancel',
// this fucntion down here 👇 gets called everytime the Cancel Button is
pressed
onPress: () => console.log('Cancel Button Pressed'),
},
{
text: 'Surprise',
// this fucntion down here 👇 gets called everytime the Surprise Button is
pressed
onPress: () => console.log('Surprise Button Pressed'),
},
]);

When you click outside of alert area, it gets cancelled. To alter this behavior of
alert, we can use this cancelable object

Alert.alert('Status', 'Successful, letting you in...', [


{
text: 'OK',
// this fucntion down here 👇 gets called everytime the OK Button is
pressed
onPress: () => console.log('OK Button Pressed'),
},
{
text: 'Cancel',
// this fucntion down here 👇 gets called everytime the Cancel Button is
pressed
onPress: () => console.log('Cancel Button Pressed'),
},
{
text: 'Surprise',
// this fucntion down here 👇 gets called everytime the Surprise Button is
pressed
onPress: () => console.log('Surprise Button Pressed'),
},
{cancelable: false},
]);

To read more about Alert, visit following links:

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';

const App = () => {


const [modalVisible, setModalVisible] = useState(false);

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>
);
};

export default App;

const styles = StyleSheet.create({


container: {
flex: 1,
paddingTop: 20,
paddingHorizontal: 10,
alignItems: 'center',
justifyContent: 'center',
},
button: {
backgroundColor: '#B01E68',
paddingVertical: 20,
borderRadius: 10,
width: '50%',
},
text: {
textAlign: 'center',
color: 'white',
fontWeight: 'bold',
textTransform: 'uppercase',
},
modal: {
flex: 1,
alignItems: 'center',
backgroundColor: '#00ff00',
padding: 100,
},
});

To read more about Modal, visit following links:

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”

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


import React from 'react';

const App = () => {


return (
<View style={styles.container}>
<Image style={styles.image}
source={require('./assets/image.jpg')} />
</View>
);
};

export default App;

const styles = StyleSheet.create({


container: {
paddingTop: 50,
},
image: {
width: 200,
height: 200,
},
});
To read more about Image, visit following links:

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

import { StyleSheet, Text, View, ImageBackground } from


'react-native';
import React from 'react';

const App = () => {


const image = { uri:
'https://random.imagecdn.app/1920/1080' };
return (
<View style={styles.container}>
<ImageBackground source={image} resizeMode="cover"
style={styles.image}>
<Text style={styles.text}>App</Text>
</ImageBackground>
</View>
);
};

export default App;

const styles = StyleSheet.create({


container: {
flex: 1,
},
image: {
flex: 1,
justifyContent: 'center',
},
text: {
color: 'white',
fontSize: 42,
lineHeight: 84,
fontWeight: 'bold',
textAlign: 'center',
backgroundColor: 'red',
},
});

To read more about Image Background, visit following links:

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

• ToastAndroid.SHORT – Toasts stays for a shorter duration on the screen.


• ToastAndroid.LONG - Toasts stays for a longer duration on the screen.

Code Example

import { StyleSheet, View, ToastAndroid, Button } from


'react-native';
import React from 'react';

const App = () => {


const handleToast = () => {
ToastAndroid.show(
'My message',
ToastAndroid.LONG,
);

};
return (
<View style={styles.container}>
<Button title="Toggle toast" onPress={handleToast} />
</View>
);
};

export default App;

const styles = StyleSheet.create({


container: {
flex: 1,
justifyContent: 'center',
},
});

To read more about Toast, visit following links:

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.

First we need to install react-native-image-picker dependency in our


app by running the following command.

npm install react-native-image-picker --save

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"/>

Here is how you AndroidManifest.xml will look like.

<?xml version="1.0" encoding="utf-8"?>


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<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.

import {launchCamera, launchImageLibrary} from 'react-


native-image-picker';

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.

import React, {useState} from 'react';


import {
StyleSheet,
Text,
View,
TouchableOpacity,
Image,
Platform,
PermissionsAndroid,
} from 'react-native';

import {launchCamera, launchImageLibrary} from 'react-


native-image-picker';

const App = () => {


const [filePath, setFilePath] = useState({});

const requestCameraPermission = async () => {


if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'Camera Permission',
message: 'App needs camera permission',
},
);
// If CAMERA Permission is granted
return granted ===
PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
return false;
}
} else return true;
};

const requestExternalWritePermission = async () => {


if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STOR
AGE,
{
title: 'External Storage Write Permission',
message: 'App needs write permission',
},
);
// If WRITE_EXTERNAL_STORAGE Permission is granted
return granted ===
PermissionsAndroid.RESULTS.GRANTED;
} catch (err) {
console.warn(err);
alert('Write permission err', err);
}
return false;
} else {
return true;
}
};

const captureImage = async type => {


console.log('Capture Image ');
let options = {
mediaType: type,
maxWidth: 300,
maxHeight: 550,
quality: 1,
videoQuality: 'low',
durationLimit: 30, //Video max duration in seconds
saveToPhotos: true,
includeBase64: true,
};
let isCameraPermitted = await requestCameraPermission();
let isStoragePermitted = await
requestExternalWritePermission();
if (isCameraPermitted && isStoragePermitted) {
console.log('Capture Image if block');
launchCamera(options, response => {
console.log('Response = ', response);
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('base64 -> ',
response.assets[0].base64);
console.log('uri -> ', response.assets[0].uri);
console.log('width -> ', response.assets[0].width);
console.log('height -> ', response.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]);
});
}
};

const chooseFile = type => {


let options = {
mediaType: type,
maxWidth: 300,
maxHeight: 550,
quality: 1,
includeBase64: true,
};
launchImageLibrary(options, response => {
console.log('Response = ', response);
console.log('Response Assets = ',
response.assets[0].uri);

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>
);
};

export default App;

const styles = StyleSheet.create({


container: {
flex: 1,
padding: 10,
backgroundColor: '#fff',
alignItems: 'center',
},
titleText: {
fontSize: 22,
fontWeight: 'bold',
textAlign: 'center',
paddingVertical: 20,
},
textStyle: {
padding: 10,
color: 'black',
textAlign: 'center',
},
buttonStyle: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 5,
marginVertical: 10,
width: 250,
},
imageStyle: {
width: 200,
height: 200,
margin: 5,
},
});
In order to work with Camera, we need WRITE & CAMERA permissions. To get
these permissions, we have created two functions named
requestCameraPermission & requestExternalWritePermission. Now, let’s take a
look at how they are working

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.

Storing Images in Database


Storing images in database is not difficult as it sounds like, all you need to do is to
store either the base64 string or the imageUri in database. Let’s take a look at how
you can store an image in a database using the image Uri but first here’s the folder
structure & the dependencies required to run this demonstration.
App.js

import React from 'react';


import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import Add from './screens/Add';
import List from './screens/List';

const Stack = createStackNavigator();

const App = () => {


return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Add">
<Stack.Screen
name="Add"
component={Add}
options={{title: 'Add User'}}
/>
<Stack.Screen
name="List"
component={List}
options={{title: 'Show Users'}}
/>
</Stack.Navigator>
</NavigationContainer>
);
};

export default App;

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'});

const Add = ({navigation}) => {


const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [filePath, setFilePath] = useState({});

useEffect(() => {
CREATE_TABLE();
// DROP_TABLE();
}, []);

const handleAddUser = () => {


if (name && email && filePath) {
ADD_USER();
setName('');
setEmail('');
setFilePath({});
} else {
ToastAndroid.show('Fill up the fields first', ToastAndroid.LONG);
}
};
const CREATE_TABLE = () => {
let query =
'CREATE TABLE IF NOT EXISTS Users(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,email TEXT NOT NULL,imageUri TEXT)';
db.transaction(txn => {
txn.executeSql(
query,
[],
(tx, res) => {
console.log('Users Table Created Successfully');
},
error => {
console.log('ERROR while creating Table');
},
);
});
};
const ADD_USER = () => {
let query = 'INSERT INTO Users(name, email, imageUri) VALUES(?,?,?)';
db.transaction(txn => {
txn.executeSql(
query,
[name, email, filePath.uri],
(tx, res) => {
ToastAndroid.show('User Added', ToastAndroid.LONG);
},
error => {
console.log('ERROR while Adding User');
},
);
});
};

const DROP_TABLE = () => {


let query = 'DROP TABLE IF EXISTS Users';
db.transaction(txn => {
txn.executeSql(
query,
[],
(tx, res) => {
console.log('Users Table Dropped Successfully');
},
error => {
console.log('ERROR while dropping table');
},
);
});
};
const chooseFile = type => {
let options = {
mediaType: type,
maxWidth: 300,
maxHeight: 550,
quality: 1,
};
launchImageLibrary(options, response => {
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;
}
setFilePath(response.assets[0]);
});
};
return (
<View style={styles.root}>
<TextInput
label="Enter name"
style={styles.nameInput}
value={name}
onChangeText={newValue => setName(newValue)}
/>
<TextInput
label="Enter email"
style={styles.emailInput}
value={email}
onChangeText={newValue => setEmail(newValue)}
/>
<View style={styles.imageContainer}>
<Text>Image</Text>
<Image source={{uri: filePath.uri}} style={styles.imageStyle} />
</View>

<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>
);
};

export default Add;

const styles = StyleSheet.create({


root: {
paddingHorizontal: 20,
paddingVertical: 10,
},
imageContainer: {
marginVertical: 20,
},
imageStyle: {
width: '100%',
height: 200,
margin: 5,
borderColor: '#472183',
borderRadius: 10,
borderWidth: 2,
},
button: {
marginVertical: 5,
},
nameInput: {
marginVertical: 5,
},
emailInput: {
marginVertical: 5,
},
});

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'});

const List = () => {


const [users, setUsers] = useState([]);
useEffect(() => {
FETCH_USERS();
}, []);
const FETCH_USERS = () => {
let query = `SELECT * FROM Users`;
db.transaction(txn => {
txn.executeSql(
query,
[],
(tx, res) => {
let resultsSet = [];
for (let i = 0; i < res.rows.length; ++i) {
let record = res.rows.item(i);
resultsSet.push(record);
}
setUsers(resultsSet);
},
error => {
console.log('ERROR');
},
);
});
};
return (
<View style={styles.container}>
<FlatList
data={users}
keyExtractor={(item, index) => index}
renderItem={showItem}
/>
</View>
);
};
const showItem = ({item}) => {
return (
<Card style={styles.cardContainer}>
<Card.Title title={item.name} />
<Card.Content style={styles.cardContent}>
<Paragraph>{item.email}</Paragraph>
</Card.Content>
<Card.Cover source={{uri: item.imageUri}} />
<Card.Actions style={styles.cardActions}>
<Button mode="contained">Delete</Button>
</Card.Actions>
</Card>
);
};
export default List;

const styles = StyleSheet.create({


container: {
marginHorizontal: 20,
marginVertical: 20,
},
cardContainer: {
padding: 10,
marginVertical: 10,
},
cardContent: {
marginBottom: 10,
},
cardActions: {
marginTop: 10,
},
imageStyle: {
width: 100,
height: 200,
},
});
Material Top Tabs Navigation
To work with Top Tabs Navigation, you'll need to add the following packages by
running these npm commands 👇
npm install @react-navigation/native
npm install react-native-screens react-native-safe-area-context
npm install @react-navigation/material-top-tabs react-native-tab-view
npm install react-native-pager-view

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';

const Tab = createMaterialTopTabNavigator();


const App = () => {
return (
<NavigationContainer>
<Tab.Navigator
initialRouteName="Home"
// ScreenOptions (Optional)
screenOptions={{
tabBarLabelStyle: {fontSize: 12},
tabBarStyle: {backgroundColor: '#ADA2FF'},
// tabBarBadge accepts a string, number or true
tabBarBadge: () => {
return (
<View>
<Text>Hello</Text>
</View>
);
},
}}>
<Tab.Screen name="Home" component={Home} />
<Tab.Screen name="Login" component={Login} />
<Tab.Screen name="Register" component={Register} />
</Tab.Navigator>
</NavigationContainer>
);
};

export default App;

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"

Your build.gradle file will look like this

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

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 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>
);
};

export default App;

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

Working with APIs


Servers that are created for serving data for external use (in websites or apps) are
often referred to as APIs or ‘Application Programming Interfaces’.

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.

Here's a simple request to fetch data from an API


const fetchData = async () => {
const response = await fetch(
`http://localhost/ProductsAPI/api/products/getallproducts`,
);
const data = await response.json();
setProducts(data);
};

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

Async Storage Methods


getItem() – for primitive data types
const getEmail = async () => {
try {
const email = await AsyncStorage.getItem('email');
console.log(email);
} catch (e) {
console.log(email);
}
};

getItem() – for non-primitive data types


const getUser = async () => {
try {
const user = JSON.parse(await AsyncStorage.getItem('user'));
console.log(user);
} catch (e) {
console.log(e);
}
};
setItem() – for primitive data types
const setEmail = async () => {
try {
await AsyncStorage.setItem('email', email);
} catch (e) {
console.log(e);
}
};

setItem() – for non-primitive data types


const setUser = async () => {
try {
const user = {
email: email,
password: password
}
await AsyncStorage.setItem('user', JSON.stringify(user));
} catch (e) {
console.log(e);
}
};

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);
}
};

Helpful Extensions for VS Code


• ES7 React/Redux/GraphQL/React-Native snippets
Simple extensions for React, Redux and Graphql in JS/TS with ES7 syntax
• React Native Tools
This VS Code extension provides a development environment for React Native projects. Using
this extension, you can debug your code and quickly run react-native commands from the
command palette.

• 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 create new react project in your computer run following command


npx react-native init yourProjectName

To run react project (on android device) in your computer run following command
npx react-native run-android

To install react native paper


npm install react-native-paper@5.0.0-rc.6

To install react native navigation


npm install @react-navigation/native

To Install dependencies of native navigation into a bare React Native project


npm install react-native-screens react-native-safe-area-context

npm install @react-navigation/native-stack


References
reactnative.dev/docs

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

Practice React Native (Exercise # 1)

Type the give code and try to understand.

import React, { useState } from 'react';


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

const App = () => {


const [name, setName] = useState('React Native')
const [session, setSession] = useState({ number: 1, title:
'React Native introduction' })
const [current, setCurrent] = useState(true)

const onClickHandler = () => {


setName('Learning React Native')
setSession({ number: 2, title: 'Components' })
setCurrent(false)
}

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>
);
};

const styles = StyleSheet.create({


body: {
flex: 1,
backgroundColor: '#0000ff',
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: '#ffffff',
fontSize: 20,
fontStyle: 'italic',
margin: 10,
},
});

export default App;

Before Button Click:


After Button Click:
Practice React Native (Exercise # 2)

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.

import React, { useState } from 'react';


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

const App = () => {


const [name, setName] = useState('Style Test')

const onClickHandler = () => {


setName('Style Test is Done!')
}

return (
<View style={styles.body}>
<Text style={styles.text}>{name}</Text>
<View style={styles.button}>
<Button title='Update State'
onPress={onClickHandler}></Button>
</View>
</View>
);
};

const styles = StyleSheet.create({


body: {
flex: 1,
backgroundColor: '#f00f00',
alignItems: 'center',
justifyContent: 'center',
borderWidth: 10,
borderColor: '#ff00ff',
borderRadius: 10,
},
text: {
color: '#000000',
fontSize: 35,
fontStyle: 'italic',
margin: 10,
textTransform: 'uppercase'
},
button: {
width: 200,
height: 60,
}
});

export default App;


Before Button Click:
After Button Click:
Practice React Native (Exercise # 3)
Type the give code and try to understand. Execute the given code in your system to
view the output.

import React, { useState } from 'react';


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

const App = () => {

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 styles = StyleSheet.create({


body: {
flex: 1,
flexDirection: 'column',
backgroundColor: '#0000ff',
alignItems: 'stretch',
justifyContent: 'center',
},
container1: {
flex: 1,
backgroundColor: '#00ffff',
alignItems: 'center',
justifyContent: 'center',
},
container2: {
flex: 1,
backgroundColor: '#ff00ff',
alignItems: 'center',
justifyContent: 'center',
},
container3: {
flex: 1,
backgroundColor: '#ffff00',
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: '#000000',
fontSize: 35,
fontStyle: 'italic',
margin: 10,
},
});

export default App;


Practice React Native (Exercise # 4)

Type the given code and try to understand.

import React, { useState } from 'react';


import { Text, View, StyleSheet, SectionList, RefreshControl } from 'react-
native';
const App = () => {
const [refreshing, setRefreshing] = useState(false);

const onRefresh = () => {


setRefreshing(true);
setTimeout(() => {
setRefreshing(false);
}, 2000);
};

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>;
};

const Header = ({ section }) => {


return <Text style={styles.taskTitle}>{section.title}</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>
);
};

export default App;

const styles = StyleSheet.create({


rootContainer: {
flex: 1,
backgroundColor: '#F6F6C9',
},
container: {
flex: 1,
marginTop: 30,
marginHorizontal: 10,
},
taskItem: {
padding: 10,
marginVertical: 15,
fontSize: 16,
},
taskTitle: {
backgroundColor: '#ffffff',
fontSize: 20,
fontWeight: 'bold',
padding: 10,
elevation: 4,
margin: 10,
marginBottom: 0,
borderRadius: 10,
},
});
Practice React Native (Exercise # 5)

Type the given code and understand it

import React, { useState } from 'react';


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

const App = () => {


const [timesPressed, setTimesPressed] = useState(0);

let textLog = '';


if (timesPressed > 1) {
textLog = timesPressed + 'x onPress';
} else if (timesPressed > 0) {
textLog = 'onPress';
}

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>
);
};

const styles = StyleSheet.create({


container: {
flex: 1,
justifyContent: "center",
},
text: {
fontSize: 16
},
wrapperCustom: {
borderRadius: 8,
padding: 6
},
logBox: {
padding: 20,
margin: 10,
borderWidth: StyleSheet.hairlineWidth,
borderColor: '#f0f0f0',
backgroundColor: '#f9f9f9'
}
});

export default App;

Practice React Native (Exercise # 6)


Here’s the folder structure for this exercise
Type the given code and understand it

App.js

import React from 'react';


import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import BookInfo from './screens/BookInfo';
import BookDetails from './screens/BookDetails';

const Stack = createStackNavigator();

const App = () => {


return (
<NavigationContainer>
<Stack.Navigator initialRouteName="BookInfo">
<Stack.Screen name="BookInfo" component={BookInfo} />
<Stack.Screen name="BookDetails" component={BookDetails} />
</Stack.Navigator>
</NavigationContainer>
);
};

export default App;

BookDetails.js

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


import React from 'react';

const BookDetails = ({route}) => {


const {item} = route.params;
return (
<View style={styles.container}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.detailsText}>Pages: {item.pages}</Text>
<Text style={styles.detailsText}>Author: {item.author}</Text>
<Text style={styles.detailsText}>Publisher: {item.publisher}</Text>
<Text style={styles.detailsText}>Price: {item.price}</Text>
</View>
);
};
export default BookDetails;

const styles = StyleSheet.create({


container: {
flex: 1,
padding: 10,
},
title: {
fontSize: 40,
fontWeight: 'bold',
textAlign: 'center',
marginBottom: 10,
},
detailsText: {
fontSize: 18,
textAlign: 'center',
marginBottom: 5,
},
});

BookInfo.js

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


import React from 'react';

const BookInfo = ({ navigation }) => {


const books = [
{
title: 'C#',
pages: 200,
author: 'Robert',
publisher: 'XYZ',
price: 1000,
},
{
title: 'Java',
pages: 150,
author: 'Robert',
publisher: 'XYZ',
price: 800,
},
{
title: 'JavaScript',
pages: 300,
author: 'Robert',
publisher: 'XYZ',
price: 1500,
},
{
title: 'Python',
pages: 200,
author: 'Robert',
publisher: 'XYZ',
price: 2000,
},
];

const Item = ({ item }) => {


const onPressHandler = () => {
navigation.navigate('BookDetails', {
item,
});
};
return (
<Pressable style={styles.itemContainer} onPress={onPressHandler}>
<Text style={styles.itemText}>{item.title}</Text>
</Pressable>
);
};

return (
<View style={styles.container}>
<FlatList
data={books}
keyExtractor={(item, index) => index}
renderItem={Item}
/>
</View>
);
};

export default BookInfo;

const styles = StyleSheet.create({


container: {
flex: 1,
marginTop: 20,
// alignItems: 'center',
},
itemContainer: {
alignSelf: 'center',
backgroundColor: 'red',
padding: 10,
margin: 10,
alignItems: 'center',
borderRadius: 10,
width: '60%',
},
itemText: {
color: 'white',
},
});

Practice React Native (Exercise # 7)

Here’s the folder structure for this exercise


Type the given code and understand it

App.js

import React from 'react';


import {StyleSheet, Text, View} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import Home from './screens/Home';
import NewPizza from './screens/NewPizza';
import TakeOrder from './screens/TakeOrder';

const Stack = createStackNavigator();

const App = () => {


return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="NewPizza" component={NewPizza} />
<Stack.Screen name="TakeOrder" component={TakeOrder} />
</Stack.Navigator>
</NavigationContainer>
);
};

export default App;

const styles = StyleSheet.create({});

NewPizza.js

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


import {TextInput, RadioButton, Button} from 'react-native-paper';
import React, {useState} from 'react';
import {openDatabase} from 'react-native-sqlite-storage';

const db = openDatabase({name: 'PizzaDatabase.db'});

const NewPizza = () => {


const [flavour, setFlavour] = useState('');
const [price, setPrice] = useState();
const [size, setSize] = useState('S');

const ADD_PRODUCT = () => {


let query = 'INSERT INTO Pizza(flavour, size, price) VALUES(?,?,?)';
db.transaction(txn => {
txn.executeSql(
query,
[flavour, size, price],
(tx, res) => {
console.log(res);
ToastAndroid.show(
'New Pizza Added Successfully!',
ToastAndroid.SHORT,
);
},
error => {
console.log('ERROR');
},
);
});
};

const submitHandler = () => {


ADD_PRODUCT();
clearFields();
};

const clearFields = () => {


setFlavour('');
setSize('S');
setPrice('');
};
return (
<View style={styles.container}>
<View style={styles.innerContainer}>
{/* Flavour */}
<View style={styles.flavour}>
<Text style={styles.text}>Flavour</Text>
<TextInput
style={styles.input}
value={flavour}
onChangeText={value => setFlavour(value)}
/>
</View>
{/* Size */}
<View style={styles.size}>
<Text style={styles.text}>Size</Text>
<RadioButton.Group
onValueChange={value => setSize(value)}
value={size}>
<RadioButton.Item label="S" value="S" />
<RadioButton.Item label="L" value="L" />
<RadioButton.Item label="XL" value="XL" />
</RadioButton.Group>
</View>
{/* Price */}
<View style={styles.price}>
<Text style={styles.text}>Price</Text>
<TextInput
style={styles.input}
value={price}
onChangeText={value => setPrice(value)}
/>
</View>
{/* Save Button */}
<Button mode="contained" style={styles.button} onPress={submitHandler}>
Save
</Button>
</View>
</View>
);
};

export default NewPizza;

const styles = StyleSheet.create({


container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
innerContainer: {
width: '90%',
overflow: 'hidden',
},
flavour: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
},
input: {
width: '70%',
},
text: {
fontSize: 18,
fontWeight: 'bold',
marginRight: 20,
},
size: {
width: '70%',
marginVertical: 20,
flexDirection: 'row',
marginLeft: 18,
},
price: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
},
button: {
marginTop: 40,
width: '40%',
alignSelf: 'center',
marginBottom: 30,
padding: 10,
backgroundColor: '#68B984',
},
});

TakeOrder.js

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


import {TextInput, RadioButton, Button} from 'react-native-paper';
import {Picker} from '@react-native-picker/picker';

import React, {useState, useEffect} from 'react';


import {openDatabase} from 'react-native-sqlite-storage';

const db = openDatabase({name: 'PizzaDatabase.db'});

const TakeOrder = () => {


const [selectedFlavour, setSelectedFlavour] = useState();
const [selectedSize, setSelectedSize] = useState();
const [flavours, setFlavours] = useState([]);
const [sizes, setSizes] = useState([]);
const [quantity, setQuantity] = useState();
const [orders, setOrders] = useState([]);
const [currentOrderPrice, setCurrentOrderPrice] = useState(0);
const [totalPrice, setTotalPrice] = useState(0);

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]);

const handleAddOrder = () => {


FETCH_PIZZA_PRICE();
const order = {
flavour: selectedFlavour,
size: selectedSize,
quantity,
};
setOrders(prev => [...prev, order]);
};

const FETCH_PIZZA_PRICE = () => {


let query = 'SELECT price FROM Pizza WHERE flavour = ? AND size = ?';
db.transaction(txn => {
txn.executeSql(
query,
[selectedFlavour, selectedSize],
(tx, res) => {
let record = res.rows.item(0).price;
setCurrentOrderPrice(record);
},
error => {
console.log('DISTINCT FLAVOURS ERROR');
},
);
});
};

const FETCH_DISTINCT_FLAVOURS = () => {


let query = 'SELECT DISTINCT flavour FROM Pizza ORDER BY flavour';
db.transaction(txn => {
txn.executeSql(
query,
[],
(tx, res) => {
let resultsSet = [];
for (let i = 0; i < res.rows.length; ++i) {
let record = res.rows.item(i);
resultsSet.push(record.flavour);
}
setFlavours(resultsSet);
setSelectedFlavour(resultsSet[0]);
},
error => {
console.log('DISTINCT FLAVOURS ERROR');
},
);
});
};
const FETCH_DISTINCT_SIZES = () => {
let query = 'SELECT DISTINCT size FROM Pizza WHERE flavour = ?';
db.transaction(txn => {
txn.executeSql(
query,
[selectedFlavour],
(tx, res) => {
let resultsSet = [];
for (let i = 0; i < res.rows.length; ++i) {
let record = res.rows.item(i);
// console.log(record.size);
resultsSet.push(record.size);
}
setSizes(resultsSet);
setSelectedSize(resultsSet[0]);
},
error => {
console.log('DISTINCT SIZES ERROR');
},
);
});
};
return (
<View style={styles.container}>
<View style={styles.innerContainer}>
{/* Flavour */}
<View style={styles.flavourContainer}>
<Text style={styles.text}>Flavour</Text>
<Picker
style={styles.flavourPicker}
selectedValue={selectedFlavour}
onValueChange={(itemValue, itemIndex) =>
setSelectedFlavour(itemValue)
}>
{flavours &&
flavours.map((item, index) => {
return <Picker.Item label={item} value={item} key={index} />;
})}
</Picker>
</View>
{/* Size */}
<View style={styles.sizeContainer}>
<Text style={styles.text}>Size</Text>
<Picker
style={styles.flavourPicker}
selectedValue={selectedSize}
onValueChange={(itemValue, itemIndex) =>
setSelectedSize(itemValue)
}>
{sizes &&
sizes.map((item, index) => {
return <Picker.Item label={item} value={item} key={index} />;
})}
</Picker>
</View>
{/* Price */}
<View style={styles.priceContainer}>
<Text style={styles.text}>Price: {totalPrice}</Text>
</View>
{/* Qty */}
<View style={styles.quantityContainer}>
<Text style={styles.text}>Quantity</Text>
<TextInput
style={styles.input}
label="Enter Quantity"
value={quantity}
onChangeText={value => setQuantity(value)}
/>
</View>
{/* Button */}
<Button mode="contained" style={styles.button} onPress={handleAddOrder}>
Add
</Button>
{/* Orders FlatList */}
<FlatList
data={orders}
keyExtractor={(item, index) => index}
renderItem={Item}
/>
</View>
</View>
);
};
const Item = ({item}) => {
return (
<View style={styles.itemContainer}>
<Text style={styles.itemText}>Flavour: {item.flavour}</Text>
<Text style={styles.itemText}>Size: {item.size}</Text>
<Text style={styles.itemText}>Quantity: {item.quantity}</Text>
</View>
);
};

export default TakeOrder;

const styles = StyleSheet.create({


container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#D6E4E5',
},
innerContainer: {
width: '90%',
overflow: 'hidden',
},
flavourContainer: {
marginVertical: 10,
},
sizeContainer: {
marginVertical: 10,
},
quantityContainer: {
marginVertical: 10,
},
flavourPicker: {
backgroundColor: '#EFF5F5',
},
text: {
fontSize: 18,
fontWeight: 'bold',
marginRight: 20,
marginVertical: 10,
},
priceContainer: {
marginVertical: 20,
},
input: {
backgroundColor: '#EFF5F5',
},
button: {
padding: 5,
marginVertical: 20,
backgroundColor: '#68B984',
},
itemContainer: {
padding: 10,
backgroundColor: '#EFF5F5',
marginVertical: 5,
justifyContent: 'space-between',
},
});

You might also like