All posts by admin


React Navigation basic example


yarn add react-navigation


npm install –save react-navigation

Creating Friends page (screen/Friends.js)

We create the Friends page. We navigate to the HomeScreen by using that string as the id.

Creating Home page (screen/Home.js)

Create a home page. Make sure any kind of text is wrapped in Text. We have a button, that upon the onPress event, navigates to our ‘FriendScreen’. This string is dictated by our AppContainer file below and used to navigate to the Friends page.


In the latest react navigation, we create an app container that houses a navigator.
We will be using this AppContainer in App.js

For the AppNavigator object, notice the properties FriendsScreen and HomeScreen. They will be used as strings ids when other screens need to navigate…like so:


Passing into AppContainer

As you can see we pass in a prop called screenProp
It is an object, which we put inside of JS expression brackets.

In this object, we pass three properties.

1) current Friends array
2) possible Friends array
3) add Friends function

Retrieving the props data

In home, we retrieve it via this.props.


In Friends, we use more of its features

Mosh React tutorial (part 2)

ref –

Handling Events

All those standard DOM events are available via the JSX.

We’ll use onClick and have it respond to our function handleIncrement.
However, when we execute the function, we notice that the this object is undefined.

Its because we need to bind the event handler.

But why is it that in an event handler function, the this object is undefined?

Depending on how a function is called, the ‘this’ changes.

The this reference will always return the calling object.

However, if the function is called as standalone, it will return window object.
If the standalone function is called within ‘strict mode’, it will return undefined.

And that is the reason, our event handler function does not have access to ‘this’.

Notice that its a handleIncrement REFERENCE. We didn’t execute the function yet. If the function was executed right away, then it will correctly call the function, and the function will be able to display this.

But for event handlers, since we pass the handleIncrement function reference, when it is used, it will be used in another function of a different environment. It will not be able have class Counter as its surrounding environment. It will be used in its own environment, namely, as a standalone function. Hence standalone functions (in a ‘strict mode’) will have undefined as the this object.

use ‘bind’ in the constructor

We implement a constructor function. Make sure you call super to initiate its parent class.
Then we bind the current this object to that function. So that when the reference of that function gets passed around, the this will always return to this object, and subsequently, the properties in this classCounter.

Use custom constructor to bind your event handlers to class Counter

Now, this.state.count will be valid.

use an arrow function

Updating the State

full code

What happens when State Changes

Let’s see what happens under the hood.

At this point, we call setState to tell React that the state of this component will change.

React will then schedule an async call to the render method. We don’t know when it happens, but it will happen in the future.

The render function will return a new React element. That element comes from the JSX code.

Hence, our virtual DOM is a div element, with span and button as its children.
We also have old virtual DOM. React will put them side by side and figure out what elements in the virtual DOM are modified.

It will notice that our span is modified because that’s where it has used formatCount().
So it will reach out to the real DOM, and update that span, in order to match what we have in the virtual DOM.

Go to the web page, Inspect Elements, and click on the ‘Increment’ button.
You’ll see that as you push the increment button, it calls

which updates the span. It updates the span because it depending on this.state.count it will update the class name to badge-primary or badge-info, and also update the count integer. Thus, in your Inspect Element, nothing else in the DOM is affected. Only that span element.

Passing Event Arguments

Mosh React tutorial (part 1)

ref –

Set up

Creating 1st app

EPCNSZXW0324:Desktop rickytsao$ create-react-app mosh-react-tut

Creating a new React app in /Users/rickytsao/Desktop/mosh-react-tut.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts…

> fsevents@1.2.4 install /Users/rickytsao/Desktop/mosh-react-tut/node_modules/fsevents
> node install

[fsevents] Success: “/Users/rickytsao/Desktop/mosh-react-tut/node_modules/fsevents/lib/binding/Release/node-v59-darwin-x64/fse.node” is installed via remote
+ react-scripts@2.1.3
+ react-dom@16.7.0
+ react@16.7.0
added 1991 packages from 684 contributors and audited 35736 packages in 139.086s
found 0 vulnerabilities

Initialized a git repository.

Success! Created mosh-react-tut at /Users/rickytsao/Desktop/mosh-react-tut
Inside that directory, you can run several commands:

npm start
Starts the development server.

npm run build
Bundles the app into static files for production.

npm test
Starts the test runner.

npm run eject
Removes this tool and copies build dependencies, configuration files
and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

cd mosh-react-tut
npm start

Happy hacking!
EPCNSZXW0324:Desktop rickytsao$

will install…

Development Server
…other tools

Now we have fully working react app..

> cd mosh-react-tut
> npm start

The app would start.

JSX (javscript xml)

– describe what UI will look like
– Babel takes JXS file, convert it to plain javascript code that browsers can understand.

Takes JXS file

convert it to javascript code:

– Babel compiles the JXS file, compile it to React Compoennt

ref –

Write React code from scratch

in src, delete all files.

In src folder, Add file index.js

babel will compile it down to a call to React.createElement.

This is why we need to import React from top.

That was the output of a JS expression. Its a React Element.
virtual DOM lightweight in memory representation of the DOM.
React Element is part of virtual DOM.

React will then compare virtual DOM vs real DOM. See what has changed, and make changes accordingly.


Thus, you will get “Hello World” printed with div id root.

In real world, we don’t render elements like this.
We render Components instead.

We also render tree of components, which produce complex markup.


First React Component

Create react app
start it up.

Open up Terminal.

Now, let’s import bootstrap into our app.

> npm i bootstrap@4.1.1


After saving, when you look at the web page, you’ll see that the font has turned purple.

In our folder view, under src, create a components folder.
Inside add a new file called counter.jsx

Earlier, we have installed Simple React Snippets…let’s use that now.

imrc + tab “import react component”
cc + tab “create class”


Notice we’re defining the class above, and exporting it below

Now, let’s import Counter into our index.js file

Go back to your web page and you should see the text from Counter component

Embedding Expressions

add button to our Counter component

Note that JSX expressions must have 1 parent element.
JSX get compiled to React.createElement() where its argument is the type of element we want to create, i.e h1.

Thus, we must wrap what we want to display inside of an element, say a div.


*Multi cursor editing – Select piece of code, press cmd + d, you’ll get multiple cursor, and change all instance in one go.

React Fragment

But let’s say you don’t like to wrap everything inside of an all encompassing element. You just want to put your fragmented code in the return expression.

Now when you look at the webpage, inspect the element, and you won’t see the div anymore.
You’ll see your html code underneath the id=root div.

Using state for dynamic data

First we override the state property in our Counter component.

We assign a property count to it.

Then in our JSX, we use curly braces and put any js expression inside of it.

save the changes, and you’ll see the results on your web page.

In between curly braces, you can write any valid javascript expression.
Hence, let’s implement a method, and use it within our curly braces.

Now, you will be able to see the string Zero when our count is 0.

We can also return JSX expression in our JS code.

JS expression like normal javascript. Pass them to a function, define const, variable…etc.

Setting Attributes

You can put set attributes via your js code as well. Let’s say we add a state property with a string to a url that generates a random image.

We put our ‘imageUrl’ property inside of the curly brace used in JSX and it will work like so:

Now, you’ll see the image in your output.

Remember that JSX gets compiled into React create element functions, which then outputs html. Hence, in our JSX, when we’re working with classes, we cannot just use class as attribute. We use ‘className’.

When we want to work with styles, we can create properties, which hold CSS data, which then changes dynamically. Those changes will be reflected in our JSX

inline styles

If you want to use inline styles, you can do another curly brace, and type in your styles like so:

Rendering Classes dynamically

We calculate bootstrap class name depending on if the count is 0 or not.
Then we render this calculation.

Thus, every time the page gets rendered, bootstrap’s “badge-warning” will be returned when the count is 0

and “badge-primary” will be returned when the count is not zero

Rendering Lists

Let’s render a list of tags.

We add new property of our state object.

JSX is NOT a TEMPLATE ENGINE, no concept of loops.

Its a simple syntax that gets compiled to React elements.

So we do it through javascript expressions via curly braces {…}

However, there is an error in the console.

Warning: Each child in an array or iterator should have a unique “key” prop.

The reason why is because it needs to uniquely identify each item in this list.
If the state of this react element changes, React needs to figure out quickly which element is changed.
And where in the DOM it needs to make changes so that it’s in sync with its virtual DOM.

Whenever you’re using the map method to render items, we need to set the ‘key’ attribute for our JSX.

Conditional Rendering – use curly braces for js expressions

Let’s spit out a message for when the tags are 0.
If there is some items in the tags array, then we simply display it.

JSX is not a templating engine. We do not have if/else. To put conditional rendering, we need to go back to our javascript.

We can add a helper method i.e renderTags().

Another technique is use condition in curly braces

The first js expression is if the boolean evaluates to true, we display a string.
The second js expression executes renderTags function.

First React Component

Create a reac component
then import bootstrap

open a terminal

npm i bootstrap@4.1.1

In file index.js:

Under src folder, create a new folder called components

in components folder, create a file counter.jsx

create basic React project

ref –

We’ll be using the create-react-app generator for this tutorial.

Make sure you have Node.js JavaScript runtime and npm (Node.js package manager) installed.

To install the create-react-app generator, in a terminal or command prompt type:

npm install -g create-react-app

This may take a few minutes to install. You can now create a new React application by typing:

create-react-app my-app-one

This may take a few minutes to create the React application and install its dependencies.

Let’s quickly run our React application by navigating to the new folder and typing npm start to start the web server and open the application in a browser:

cd my-app-one
npm start

You should see “Welcome to React” on http://localhost:3000 in your browser. We’ll leave the web server running while we look at the application with VS Code.

To open your React application in VS Code, simply open the VS Code application and open the my-app-one folder.

Debugging React

To debug the client side React code, we’ll need to install the Debugger for Chrome extension.
Open the Extensions view and look for “Debugger for Chrome extension” in the search box. You’ll see several extensions which reference Chrome.
Press the Install button for Debugger for Chrome. The button will change to Installing then, after completing the installation, it will change to Reload. Press Reload to restart VS Code and activate the extension.

Set a breakpoint

To set a breakpoint in index.js, click on the gutter to the left of the line numbers. This will set a breakpoint which will be visible as a red circle.

Configure the Chrome debugger

We need to initially configure the debugger. To do so, go to the Debug view and click on the gear button to create a launch.json debugger configuration file. Choose Chrome from the Select Environment drop-down list. This will create a launch.json file in a new .vscode folder in your project which includes a configuration to launch the website.

We need to make one change for our example: change the port of the url from 8080 to 3000. Your launch.json should look like this:

Ensure that your development server is running (“npm start”). Then press fn+F5 or the green arrow
to launch the debugger and open a new browser instance. The source code where the breakpoint is set runs on startup before the debugger was attached so we won’t hit the breakpoint until we refresh the web page. Refresh the page and you should hit your breakpoint.

Currying and Partial Functions (js)

ref –

Partial Functions

ref –

Partial application is the act of taking a function which takes multiple arguments, and “locking in” some of those arguments, producing a function which takes fewer arguments. For instance, say we have this function:

base ^ exponent

This is partial application: we create square by making a new function, which just passes its arguments through to another function, adding some hard-coded arguments to that other function.

you can go one step further and create a partialApply function.

Now, some might begin to think that the number of nested functions a curried function has depends on the number of arguments it receives. Yes, that makes it a curry.

I can design the curried function of volume to be this:

So it can be called like this:

const hCy = volume(70);



We just defined a specialized function that calculates a volume of any cylinder of length (l), 70.

It expects 3 arguments and has 2 nested functions, unlike our previous version that expects 3 arguments and has 3 nesting functions.

This version isn’t a curry. We just did a partial application of the volume function.

Currying and Partial Application are related, but they are of different concepts.

Partial application transforms a function into another function with smaller arity.


Named after Haskell Brooks Curry, currying is the process of breaking down a function into a series of functions that each take a single argument. In other words, Currying is a technique of evaluating function with multiple arguments, into sequence of function with single argument.

In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth, until all arguments have been fulfilled.

That is, when we turn a function call add(1,2,3) into add(1)(2)(3) . By using this technique, the little piece can be configured and reused with ease.

Why it’s useful ?

Currying helps you to avoid passing the same variable again and again.
It helps to create a higher order function. It’s extremely helpful in event handling.
Little pieces can be configured and reused with ease.

Currying example

Here’s a simple example. We’ll write a function sum3 takes three numbers and returns their sum.

In a standard way, the function is implemented like so:

However, if we provide too few parameters, or too many parameters, then it can have unintended consequences.

add(1,2) –> NaN
add(1,2,3,4) –> 6 //Extra parameters will be ignored.

The curried version of sum3 behaves a differently. It accepts one argument and returns one function. The returned function also accepts one argument and also returns another function that also accepts one argument and …

This cycle continues until the returned function accepts the last argument. The last one in the chain, finally returns the sum.

This works because JS supports closures.

Currying is a transform that makes f(a,b,c) callable as f(a)(b)(c). JavaScript implementations usually both keep the function callable normally and return the partial if arguments count is not enough.

Another example of why currying is useful

Of course, currying comes in handy when you want to:

1. Write little code modules that can be reused and configured with ease, much like what we do with npm:

For example, you own a store🏠 and you want to give 10%💵 discount to your fav customers:

When a fav customer buys a good worth of $500, you give him:

You see that in the long run, we would find ourselves calculating discount with 10% on a daily basis.

We can curry the discount function, so we don’t always add the 0.10 discount:

Now, we can now calculate only with price of the goods bought by your fav customers:

Again, it happens that, some fav customers are more important than some fav customers- let’s call them super-fav customers. And we want to give 20% discount to our super-fav customers.

We use our curried discount function:

We setup a new function for our super-fav customers by calling the curry function discount with a 0.2 value , that is 20%.

The returned function twentyPercentDiscount will be used to calculate discounts for our super-fav customers:

2. Avoid frequently calling a function with the same argument:

For example, we have a function to calculate the volume of a cylinder:

To resolve this, you curry the volume function(like we did earlier):

We can define a specific function for a particular cylinder height:

How does Curry work?

Currying works by natural closure.The closure created by the nested functions to retain access to each of the arguments.So inner function have access to all arguments.

Additional Examples

ref –

You can see how powerful this approach is, especially if you need to create a lot of very detailed custom functions.
The only problem is the syntax. As you build these curried functions up, you need to keep nesting returned functions,
and call them with new functions that require multiple sets of parentheses, each containing its own isolated argument.
It can get messy.

To address that problem, one approach is to create a quick and dirty currying function that will take
the name of an existing function that was written without all the nested returns.
A currying function would need to pull out the list of arguments for that function,
and use those to return a curried version of the original function:

Currying is an incredibly useful technique from functional JavaScript.
It allows you to generate a library of small, easily configured functions that behave consistently,
are quick to use, and that can be understood when reading your code. Adding currying to your coding practice
will encourage the use of partially applied functions throughout your code, avoiding a lot of potential repetition,
and may help get you into better habits about naming and dealing with function arguments.

functions are first class objects (js)

ref –

Functions as First-Class Objects in JavaScript: Why Does This Matter?

In computer science, a programming language is said to support first-class functions (or function literal) if it treats functions as first-class objects.

First class objects are entities that can be dynamically created, destroyed, passed to functions, returned as a value, have all the rights as other variables in the language. Same as any other objects. It can have properties, methods.
In other words, this means that JS supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions. In other words,

First-class citizenship, within the world of programming, means that a

given entity (such as a function) supports all the operational properties inherent to other entities; properties such as being able to be assigned to a variable, passed around as a function argument, returned from a function, etc.

Basically, first-class citizenship simply means “being able to do what everyone else can do.”

Excellent! But okay… who cares if JavaScript functions are first-class objects? What does it matter?

The beauty of JavaScript functions enjoying first-class citizenship is the flexibility it allows.

Functions as first-class objects

opens the doors to all kinds of programmatic paradigms and techniques that wouldn’t otherwise be possible.

– Functional programming is one of the paradigms that first-class functions allow.

– Additionally, listening for and handling multiple events by passing callback functions is a useful feature within JavaScript and is achieved by passing a function as an argument to the document object’s addEventListener method.

for example, we have a form with id msgbox. It takes text input, and when you press the submit button, it’ll send a “submit” event.

What we try to do, is listening for that event, and get the data from the form.

This is where we pass the SendMessage function as a argument to the addEventListener method.

Where callback functions SendMessage implementation is:

Once we have listened in on the ‘submit’ event, we call SendMessage function in order to create a CustomEvent object with id “newMessage”, stick the user text into it, and then dispatch the event. Now, whoever is listening in on Events with id “newMessage” will be able to receive that event.

So we have a div to put all our text in.

Then we have this div listen for “newMessage” events.
Whenever we get “newMessage” events, we want to call newMessageHandler function.

Now, the callback function newMessageHandler has parameter event e, which is the CustomEvent itself.
Take note that the CustomEvent is of an object with properties details, bubbles, and cancelable.

so in newMessageHandler, we have parameter Event e object. This object is

So in newMessageHandler, we then access the msg via detail property via

– Furthermore, the practices of closure and partial-application/currying would not be possible within JavaScript if functions didn’t enjoy the status of first-class.

ref –
Closure example


The result is:

1 second later…


The reason why is because the for loop does 2 things:

1) print out the i
2) set up an async execution of a function that prints i.

The reason why you get 0-9 in the beginning is due to 1). It prints the i right away.
Then it will set up 10 async execution of the callback function.

Once the 1 second passes, it will run the callback.
The reason why the 10 callback functions will all print out all 10s, is because i is already at 10.

The inner function in the setTimeout references the i via parent scope.

The next thing we can do is execute the function expression via IIFE right away like so:

Now, due to executing the inner function right away, we’ll get the results like so:

for loop: 0
callback: 0 √
for loop: 1
callback: 1 √
for loop: 2
callback: 2 √

When the 1 second passes, it won’t execute the inner function because it was already executed.
The reason why i logs correctly is because we not waiting until it hits 10. We are referencing i right at the moment of the loop, and not after the looping is done.

However, this isn’t exactly what we want.

What we want to do is this. Everytime the for loop sets up an inner function for setTimeout, we know that having the inner function referencing i won’t work because 1 second later, i will already be 10. What we want to do is save the state of the i right at the instant the loop is happening. Hence, what we want to do is:

1) use IIFE to pass in a parameter where we store index i. It will execute this IIFE right away. But since it executes right away, similar to the last example, wouldn’t setTimeOut not be able to execute it?

2) That’s the trick. We return a function to be executed by the setTimeout. 1 second later, the returned function will execute. That function will log index, which has saved state.


for loop: 0
execute inner function: 0 √
for loop: 1
execute inner function: 1 √
for loop: 2
execute inner function: 2 √
for loop: 3
execute inner function: 3 √
for loop: 4
execute inner function: 4 √
for loop: 5
execute inner function: 5 √
for loop: 6
execute inner function: 6 √
for loop: 7
execute inner function: 7 √
for loop: 8
execute inner function: 8 √
for loop: 9
execute inner function: 9 √

1 second later …

execute return function: 0
execute return function: 1
execute return function: 2

In conclusion, due to us being able to return functions as objects, and passing them as parameters, functions as firsts class objects allows closures to happen.

Currying Example

ref –


In JavaScript, functions are objects (hence the designation of first-class object). They inherit from the Object prototype and they can be assigned key:value pairs. These pairs are referred to as properties and can themselves be functions (i.e., methods).

And as mentioned, function objects can be assigned to variables, they can be passed around as arguments; they can even be assigned as the return values of other functions. Therefore, functions in JavaScript are first-class objects.

Additionally, functions are a type of object with two special properties, name and code. A function can be named or anonymous. If it’s named then the name will be stored in name property and the code we want to execute will be stored in code. When we try to invoke a function , JavaScript will try to execute the code segment in the code property.

Since functions are a type of objects, we are able to attach properties to the functions. As you can see in the above image, there are several properties and methods in the “myFunction” function.

We can use the function’s prototype property to store our methods which are common to all objects created using this function. This will help to save all the methods in one place and helps us to reduce the memory footprint of our objects since our methods are stored in the prototype not in the individual objects.

Open up a browser, and open up Elements. Then type in:

When you analyze the instance of a, you’ll see the structure and hierarchy. The black box is the instance. It has a __proto__ property that is red. It points to the prototype object of MyFunction.

Under the prototype property, you’ll see properties constructor and __proto__.
MyFunction’s constructor property points back to MyFunction’s constructor function.
The __proto__ points down to object prototype.

From an Object structure point of view, in Chrome Elements, it looks like this:

Diagram wise, it looks like this:

We then add a property to the instance. As you can see, the property belongs to the instance. Each instance will have its own “nickname” property.

Finally, we add a function to the prototype. This means all instances of MyFunction can share/use this singular function.

  • A function is an instance of the Object type
  • A function can have properties and has a link back to its constructor method
  • You can store the function in a variable
  • You can pass the function as a parameter to another function
  • You can return the function from a function

Having functions as type of object helps us to pass our functions into another functions as arguments and open new possibility of writing good programs. I hope you got little more understanding of functions in JavaScript. If you like the article or have any suggestions on improving my article, please reply to this article or contact me.

Storing a function

Functions can be stored in three ways:

store in a variable :

store in an object :

store in an array :

In the first and third example, I used a named function expression.
The function expression defines a function as part of a larger expression. The line of code doesn’t start with function .

Function as an argument

In the next example, the function doSomething is sent as an argument to doAction().

A callback is a function passed as an argument to another function.

Higher order functions

A higher order function is:
1) a function that takes another function as an input,
2) returns a function or does both.

Let’s look at some built-in methods that are higher-order functions : filter(), map() and reduce().

filter() takes elements out from a list based on a function that decides if the value should be kept.