React.js Study Note

吳定群
11 min readJun 16, 2021

React Learning Path

From Codevolution

DOM(Document Object Model)

The way that javascript get connected to html.

Start

Build a folder. Go to terminal run following code.

create-react-app .

Then we can run npm run start. It will open in the browser.

render() function

ReactDOM have this “render” function which allow us render something out onto the browser. The first thing in render is what you want to put. Second thing is where you want to put.

“Hey ReactDOM!! I want you to render the string “hello world” into the reactContentRoot.”

const reactContentRoot = document.getElementById('root')ReactDOM.render("hello world", reactContentRoot)

React.createElement()

React.createElement() will allow us to create the html element.

JSX

JSX is a syntax that very similar to html. We use it in the javascript file. If we want to use JSX syntax, we need to import react.

import React from 'react';

Component

In react, component represent the part of the user interface. Generally, a website have 5 component. Header, Side Navigation bar, Main content, Footer and the root component. All of the components are reusable.

Component Types — Function & Class.

Transition — Turn function component into class component.

  1. Create an ES6 class, with the same name, that extends React.Component.
  2. Add a single empty method to it called render().
  3. Move the body of the function into the render() method.
  4. Replace props with this.props in the render() body.
  5. Delete the remaining empty function declaration.
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}

Compare

Functional Components

Functional component is just a javascript function. It access input as properties(props) and return Html (JSX because in javascript file) which describe the user interface.

import and export component

This means the “List3” code can be used in different file(in our src folder). Don’t forget “./”

import List3 from './info'export default List3

if we directly export the function, we have something different when we import it.

export const Greet = ()=>{   return(      <h3>hello World</h3>   )}

Now we import Greet function. We need {} outside Greet.

import { Greet } from './greet'

useState()

“useState” function is an array. It have two element in the array. First one is the actual state variable we’re gonna use. The other one is the function which tell react to update the variable.

So now we store 0 into “currentCount” ; store update function into “setCurrentCount”(second line). Update function is used to update variable onto UI. 0 is default value.

Summary : When we click the button, I want to call “handleClick” function. In the “handleClick” function, “setCurrentCount” is a update function which update variable “currentCount” onto UI.

Do CSS styling in Javascript

In javascript, color: “blue” is an object. color is key and “blue” is value. So we need “”. It will be a little bit different with CSS.

Remember that we can’t write “-” in Javascript. Ex: text-align need to be textAlign

<div style={{textAlign: 'center'}}>

Conditional Rendering

We can put a true/false operator before “?”. After the “?”, we put two conditions between “:” If it’s true, return the first one. Let see how it does.

Now this.state.login is false. Return “Welcome Visitor”

Otherwise, if we want to render either something or none, we can use &&. Now because login is true, we render Welcome Sam.

map()

map() calls a defined call-back function on each element in an array.

filter()

It can return true or false for each element in the array. If true, element will stay in the array. Otherwise, element will get removed from the array.

key & list (when you using map function..)

Each item in the list which is rendered by map operator have a props call key. The value of the key props need to be unique in the list. Most of the time, the id of the item will be assigned to the key props.

But what if we don’t have id and there are the same thing in the list. For example:

const names = ['Bruce', 'Bruce', 'Clare']

We can assign the index when we call map()

props

Props is an object that contain attribute and value which has been passed into component. Just like function parameter.

Props is function parameter. We can define our own attributes & assign values though props. Props is immutable, which means it can’t be change.

We can also de-structure the props. (look better)

Children Props

props in functional component
props in class component

Props vs State

State

State is variables declared in the class body. It can only used in class component. We can use state to render the thing we want on the screen. super() is used to initialize this so it need to be called before this.state(). We use constructor() to build a state.

Constructor

When we want to create a state, we will need to call it. The constructor() has two main uses.

  1. Initialize state
  2. Binding the event handler : .bind(this)

When we call constructor(), don’t forget to overwrite this.state using super().

Then we can render what we want.

setState()

An update function which update the new state to the user interface. After updating, we can run the callback function which is the second parameter of setState().

“I want to update count onto the screen. After updating the value, console log callback value”.

Binding Event handler — “this” is undefined

You have to be careful about the meaning of this in JSX callbacks. If you forget to bind this.increment and pass it to onClick, this will be undefined when the function is actually called.

Now we can render it out. Success!!

this keyword is undefined in event handler

<Link>

<Link> renders an <a> with a real href. If we have 3 “pages” handled by the router: a home page, an about page, and a users page. As you click around on the different <Link>s, the router renders the matching <Route>.

Async & Sync

Sync : The tasks must be executed in order, and the next tasks must wait for the completion of the previous tasks.

Async : The latter tasks don’t have to wait for the previous ones. They perform their own tasks.

We can write sync in async though “await”

async function a(){   
await b(); ..... // 等 b() 完成後才會執行
await c(); ..... // 等 c() 完成後才會執行
};

Async & Sync concept in Javascript

Javascript is a single thread language which means only one statement can be execute at a time.

Now think about a scenario, some of statements take time when we executed just like following. It might take 3~5sec for statement2 and statement3.

What asynchronous function do is the browser will take this request outside the block of single thread and deal with it. Because statement2 run in different part of the browser, Javascript can run statement3 continuously.

promise

Promise has two outcomes. One is “resolving” which means we get the data, and the other is “reject” which means we get some error. We can use promise to fetch data. For example:

const get_sth = () =>{  return new promise((resolve ,reject)=>{
//fetch some data
resolve('some data') reject('some error') })

Then we can use call get_sth and use .then which will be fired if we resolve the promise. We can also use .catch which will be fired if we reject the promise(get the error)

get_sth().then(data=>{  console.log(data)}).catch(err=>{  console.log(err)})

Fetch method

  1. fetch( ‘data.json’ ) get back a promise
  2. fired .then function
fetch('data.json').then(data=>{  console.log(data)}).catch(err=>{  console.log(err)})

Async Await Method

When we call async function, it will always return a promise. We will wait fetch process finish before assign to response. It’s sequentially.

const get_todo = async () =>{  const response = await fetch('todo.json')  const data = await response.json  return data})get_todo()
.then(data => console.log(data))
.catch(err => console.log(err.message))

Lifecycle Method

When we build a component…

Step1. constructor

Step2. render

Step3. componentDidMount

Step4. componentDidUpdate

4 main method definition
function for lifecycle method

componentDidMount()

It’s invoked(調用) immediately after a component is mounted(安裝) which means all components have already been rendered to the DOM. It will be called only once in whole lifecycle of event component.

componentDidUpdate()

It will be called only once in each re-render cycle.

Side Effects

Side effects are basically anything that affects something outside of the scope of the current function that’s being executed. In our dashboard, this includes:

  • API requests to our backend service (Fetching data from an API, communicating with a database)
  • Calls to our authentication service
  • Error tracking calls to Sentry

We can use pure function to think of side effects. A pure function is a function, that when given an input, will always returns the same output. But side effect will change things outside of your function which make function impure.

link : https://maxrozen.com/fetching-data-react-with-useeffect

Fragment

Fragment let you group a list of children element without adding extra note at the dom.

For example, if we put two parent element together. It will get error.

We can use div tag but it will create additional tag between div root and your parent element. Using fragment can solve this problem. <> </>is equal to <React.Fragment><React.Fragment/>.

React and HTTP

How react work with http is an important question. When we build a web application, we always want to fetch some data or send some data to server base on user interaction. React just a library for build UI, so we need Http Library to make AJAX request (or how do we make api called in react).

Now we want to fetch the api. We want to use componentDidMount(). First, axios.get()access the api end point. We use .then()to access the response and use .catch()to handle the error.

Now we can check out the console. There is an object. Inside the object is data, headers, ..etc.

We update the data on our user interface. At the end, render!!

All

Async Await function

await : It will await data

Ref — Add Ref on normal html element

We can bind Ref with something inside the render(). Then we use focus() to let user focus on the thing inside the render().

Step1 : create ref

constructor(props) {super(props);this.inputRef = React.createRef()}

Step2 : bind with input

<input type='text' ref={this.inputRef}/>

Step3 : After everything been mounted. Using focus() focusing the input box.

componentDidMount(){this.inputRef.current.focus()console.log(this.inputRef)}

Summary :

React Router

Normally on website, when we want to go about page, we need to fetch the about page from the server. React Router allow you to do something different. We can just load specific component when we click certain page so that we don’t need to go out to fetch data.

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

Put everything you need to route inside the BrowserRouter tag.

Route can render the thing based on url.

Using route to add the path for page.

Switch : Renders the first child <Route path= ‘’> that matches the location.

exact : Only the path which match exactly we render.

Link the page in the nav bar using Link. Make sure import { Link } from ‘react-router-dom’

Callback Function

A “callback” is any function that is called by another function which takes the first function as a parameter. A lot of the time, a “callback” is a function that is called when something happens. That something can be called an “event” in programmer-speak.

What cause re render

React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.

After the initial mounting of components, a re-render will occur when:

  • A component’s setState() method is called.
  • A component’s forceUpdate() method is called.

--

--

吳定群

Tsing Hua University Master for Engineering | ML & statistic | Data Science