I guess this was probaly you during the past few weeks

memeCry

Don't worry this is a common trait of a JavaScript developer. So common that there is actually a fix to this issue. Check the pro tip below in the next slide

memeUnderwater

All jokes aside let's us refresh ourself with some JS revision.

Functions

console.log("a default function that log something to the console");

function ourFunction() {
  //this is a function that do and return nothing
}

function valueFunction() {
  return "this is a function that return this string";
}

console.log(valueFunction());
// this is : log to the console, the value returned after execute the valueFunction

function withArgument(x) {
  // this function , when reveive argument will make a variable named x
  // the value of x is the value of the executing agurment;
  // and x is usable inside this function scope.
  // finally, the function return a value which is the value that x pointing to
  return x;
}

withArgument(3);
// this return 3, but we can't not see just yet.
console.log(withArgument(3));
// this is : log to the console, the value returned after execute the withArgument(3).
// Which is 3

function myFunc(wontBeUse) {
  console.log(
    "inSide of a function, this is also called a Side Effect of the function"
  );
  return 3;
}

myFunc();
// notice that we could execute a with-argument-function without giving argument
//(also called parameter) if there is no usage of the paramenter

Arrow function

//this is a function that do and return nothing
const myArrow = () => {};

const valueArrow = () =>
  "this function RETURN this string not NOT DISPLAY to CONSOLE";

const valueArrowR = () => {
  return 3;
};
console.log(valueArrowR(), valueArrow());
// this is : log to the console, the value returned after execute the
// valueArrowR and valueArrow. which is 3 and the string

const withArgument = (x) => {
  // this function , when reveive argument will make a variable named x
  // the value of x is the value of the executing agurment;
  // and x is usable inside this function scope.
  // finally, the function return a value which is the value that x pointing to
  return x;
};
console.log(withArgument(3));
// this is : log to the console, the value returned after execute the withArgument(3).
// Which is 3

const myFunc = (wontBeUse) => {
  console.log(
    "inSide of a function, this is also called a Side Effect of the function"
  );
  return 5;
};

myFunc();
// notice that we could execute a with-argument-function without giving argument
//(also called parameter) if there is no usage of the paramenter

Object and Array

const example = {
  hi: "my name is",
  abc: "slim shady",
};

// what is abc value?
const myFunc = (abc) => {
  console.log("Result is : ", abc);
  return 200;
};

myFunc("Hi"); // so abc of myFunc is "Hi"

myFunc({ x: "ha ha", y: 1 });
// so abc of myFunc is an object {x:"haha",y:1}
myFunc(example);
// so abc of myFunc is the object example {hi:"haha",abc:1}

const newFunc = (abc) => {
  console.log("Result is :", abc.hi);
  return 200;
};
newFunc(example);
//console log is "slim shady"
newFunc({ haha: "huhu" });
// !! there is no: hi key in the {haha:"huhu"} object
// so console log abc.hi is undefined

//1. This one is the same

const abc = example.abc;
const destructoringParameter = (abc) => {
  console.log(abc); //output : slim shady
};
destructoringParameter(abc);

//2. This one is the same
const { abc } = example;
const destructoringParameter = ({ abc }) => {
  console.log(abc);
};
destructoringParameter(abc);

If you have any question relating to the content above, please reach out to your TA and Instructor. These concept are crucial for our success.

React concepts:

When it comes to why one choose a library from an ocean of millions others, the debate could last even longer than the life of the choice itself. Here is a few reasons that make React one of the best choice.

Easy to learn, easy to use

Think about how you've previously interacted with the DOM, without the help of a framework. You maybe used vanilla JavaScript to manipulate text or class names based on event listeners applied to certain selectors.

Standard methods of DOM manipulation are tedious, slow and fragile. It requires us to manually target elements, it takes a long time for the browser to process DOM manipulations, and the amount of code it requires makes it really fragile. There are too many places where we could go wrong with a simple typo.

A big benefit of React is how well it can handle DOM manipulations in an easy way and efficient way. This is done through the use of a Virtual DOM.

React is a JavaScript library

This mean that learning React will improve your JavaScript skills and practicing JavaScript could also benefit your React capabilities. You spend less time studying new API but more time practicing JavaScript and React.Two bird one stone.

two-bird

From web to mobile

React skills and logics are also transferable when it comes to mobile development (IOS and Android) with React Native. React web developer could deploy their first IOS/Android Native mobile application in less than 1-2 weeks of researching. Three birds one stone.

Ohhh It's hot!!

Facebook developers, yes they made React , took care of training React on the "how" before 2015 and still improving it since. In short : unlimited amount of "resources" to keep React relevant and efficient. Other small tech companies like Netflix, Tweeter, Airbnb, Uber, Netflix, Pinterest, PayPal, Stripe, Tumblr ... are also made of React. Which lead to the fact that..

reactWanted

In the next session, we will building our first react app to demonstrate some basic examples.

Let pause before starting our next session.

React was born in 2013. So what do we have before it?

Old website

oldwebsite Back to 19s early 2000, web is just basic HTML, CSS and Javascript. Initially, it just started with simple modal where we send from the back end.

When we go to a URL, all these files (html, css, js) will be send from the back end. When a user submits data, we simply send that data back to the server to store that information. If a user clicked on a link in the page, we simply request the new HTML file and the new page from the server and that gets sent to the front end.

That's how websites worked for many years.

Morden website

modernwebsite

Developers started building bigger and bigger applications instead of just something small. We started getting those massive applications like Facebook where you got to log in, look at the news feed, message your friends. And as websites turn into these full applications that people can interact with, besides just requesting more and more pages like a blog What generally happened now is we focus less on HTML and a lot more in JavaScript.

You only load the application code once. Instead of us making new requests to the server, our applications act more like a desktop application, where we stay on the same page the entire time and the JavaScript file simply changes or updates the HTML file or the DOM to display new things.

So you are able to interact with the web app without ever speaking to the server. This way of writting application is called Single Page Application (SPA). React is also built base on this concept.

Note

Let's start with background. React is a JavaScript library for building user interfaces.

A user interface a.k.a UI is the thing we display to our end user for them so interact with our program. It is anywhere from your favorite game on laptop, indicator on the traffic light, button on your microwaves or navigation panel on your dream Mercedes.

This is what we have been doing the past 4 weeks :

document.createElement("h1");

document.getElementById("theOne");

setInterval(function () {
  console.log("yes, setInterval is a Web APIs function");
}, 1000);

This coding process is telling your browser exactly what-to-do.

With React, we make our app with some main principle:

  1. We simply telling React what-we-want. React then will then build the display User Interface in the Web Browser. This make React "declarative". Because, once again, we describe to React the UI we want, not how to do it. This can be achived with the help of virtual DOM
  2. Second, the whole app will be built like lego blocks - components

Let's find out more in the next section

Recap about DOM

The DOM (Document Object Model) is an interface that allows JavaScript to read and manipulate the content of a document (in this case, an HTML document).

Whenever an HTML document is loaded in the browser as a web page, a corresponding DOM is created for that page. This is simply an object-based representation of the HTML.

This way, JavaScript can connect and dynamically manipulate the DOM because it can read and understand its object-based format. This makes it possible to add, modify contents or perform actions on web pages.

Every time the DOM changes, the browser would need to recalculate the CSS, run layout and repaint the web page, which is not good for the performance.We need a way to minimize the time it takes to repaint the screen.

Virtual DOM

With React, it says: "hey, don't touch the DOM, I'll handle it. Just let me know what do you want."

The virtual DOM (VDOM) is a representation of the actual DOM.

It uses a strategy that updates the DOM without having to redraw all the webpage elements. This ensures that the actual DOM receive only the necessary data to repaint the UI.

virtualDOM

Whenever a new element is added to the UI, a virtual DOM is created. Now, if the state of this element changes, React would recreate the virtual DOM for the second time and compare with the previous version to detect which of the virtual DOM object has changed.

It then updates ONLY the object on the real DOM. This has a whole lot of optimization as it reduces the performance cost of re-rendering the webpage.

virtualDOM

Remember "Divide and Conquer" programming mindset? In React, we devide our entire app into components. These components are much different than our sematic tags section in HTML or nav .etc...

Your landing page project was great, it have 3-4 sections clearly defined and easy to manage. However, imagine a E-commerce website, how many pages, sub-pages translating into how many sections? Then those section must live inside your index.html file , how many lines of code would the project be.

over900

In React, we would see our entire application is a collection of many components and these components are resuable. Which means, you may only need to code the "Home" button once, then import to use it across the web.

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

function Welcome(props) {
  return <h1>Hello World</h1>;
}

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.

Note:

You could read this React Official Document Or blindly follow the instruction below :

  1. Check if you have node and npm (node package manager)
#check your node version
node --version

#check your node package manager version
npm --version
  1. Let make a new directory to store your first React project
cd yourPlace
mkdir yourProjectDirectory
cd yourProjectDirectory

  1. Enlarge your terminal to full screen and let's cast the spell to create react app.
# To create a React project in this current folder
npx create-react-app .
# To create a React project in a new folder with new name in side this folder
npx create-react-app projectName
  1. Let's wait and pray to any gods in existence, mine is React God, until we have this

success

  1. We will test run this application with
npm start

reactdone

Common bug :

reactbug

"Have you check that you run NPM start in your React project directory?"

For example, this code renders "Hello" on the page:

function Welcome(props) {
  return <h1>Hello</h1>;
}

const element = <Welcome /> // this is called React element
ReactDOM.render(element, document.getElementById("root"));

What happens in this example:

If using ReactDOM render, we would treat that function as a component of the document (like making a custom HTML tag) if we use it according to the syntax.

But wait, why the Welcome function return a HTML tag (h1)? Or is it?

Actually no. It's JSX

Notice:

stop

So what is JSX? A new language?

Introducing JSX

JSX is a mix of JavaScript and XML (Extensible Markup Language) that facilitates rendering the appropriate HTML

JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.

JSX produces React "elements". It is a syntax extension to JavaScrip to describe what the UI should look like.

function Welcome(props) {
  return <h1>Hello</h1>; // this is JSX
}

const element = <Welcome />
ReactDOM.render(element, document.getElementById("root"));

Embedding Expressions in JSX

You can put any valid JavaScript expression inside the curly braces in JSX:

const name = "Jon Snow";
const element = <h1>Hello, {name}</h1>;

ReactDOM.render(element, document.getElementById("root"));

Note: the different between expression and statement in short

Example:

{}=={}  //false
myfunc("a", "b") // myfunc function returns a value, it can be anything: null, undefinded, NaN...

Example: Loops and if statements are examples of statements. Because they don't result any value unless you wrap it in a function. OR you can use Ternary Expression

Here how it looks like in plain JavaScript:

let condition = true;
console.log(
  condition == true ? "value when it is true" : "value when it is false"
);

The ? replace the if and the : represent your else. The conditional statement is before the ? and the returning value are seperated with the :

And here is how we use Ternary Expression in JSX

const myNotification = (props) => {
  let condition = "some input from user";
  return (
    <div>
      {condition ? (
        <div>True</div>
      ) : (
        <div>False</div>
      )}
    </div>
  );
};

Truthy, Falsy

Another example:

function formatName(user) {
  return user.firstName + " " + user.lastName;
}

const user = {
  firstName: "Robb",
  lastName: "Stark",
};

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

ReactDOM.render(element, document.getElementById("root"));

Attributes

React DOM uses camelCase property naming convention instead of HTML attribute names.

For example, class becomes className in JSX

const element1 = <div className="title"></div>;
const element2 = <img src={user.avatarUrl}></img>;

Note: Don't put quotes around curly braces when embedding a JavaScript expression in an attribute.

function MyComponent(props) {
  let message =
    "Hey! because components are also function, so before returning JSX value \n I could perform some side effect as well \n Check the console";
  console.log("For example i could console log");
  let x = Math.floor(Math.random() * 10);
  return (
    <div>
      <h1>React requrire only ONE JSX value per component</h1>
      <h4>So we get around that by wrap everything in 1 element </h4>
      <button>Value of x: {x} </button>
      <p> {message} </p>
    </div>
  );
}
d
ReactDOM.render(<MyComponent />, document.getElementById("root"));

want

props is similar to our function argument, the input data we giving when using a function. In a React component, props is the input data we giving when using a component.

The only different between the two is that a props is always an object. It use to hold a collection of key and value pair passed to it by the caller.

const WithProps = (props) => {
  //we could check the props property
  console.log(props);
  return (
    <div>
        <div>{props.myName}</div>
        <div>{props.myAge}</div>
    </div>
  )
};

ReactDOM.render(
  <WithProps myName={"Arya"} myAge={19} />,
  document.getElementById("root")
);

There is another way to deal with props by using destructuring assignment.

const WithProps = ({myName, myAge}) => {
  return (
    <div>
        <div>{myName}</div>
        <div>{myAge}</div>
    </div>
  )
};

ReactDOM.render(
  <WithProps myName={"Arya"} myAge={19} />,
  document.getElementById("root")
);

Props are Read-Only

The component must never modify its own props.

read-only

Consider this sum function:

function sum(a, b) {
  return a + b;
}

Such functions are called pure because they do not attempt to change their inputs, and always return the same result for the same inputs.

In contrast, this function is impure because it changes its own input:

function withdraw(account, amount) {
  account.total -= amount;
}

React is pretty flexible but it has a single strict rule:

All React components must act like pure functions with respect to their props.

Of course, application UIs are dynamic and change over time. But it should be state changing, not props. We will be introduced a new concept of "state" later. But in short, State allows React components to change their output over time in response to user actions.

There is/was another way to make React components. However, Class component have a harder learning curve especially for beginner who have less computer science backround since it dealing with OOP - Object Oriented Programming concept. Good news for us, eventhough React will not delete Class components anytime soon but React official site recommend newer project should use Functional component instead.

You could read more on this via these resources

For now, let stick with functional component.

Don't you remeber that we cloned Sportify website in week 1. Now take that as reference, we implement Sportify again but using React this time.

suprise