Ad

Saturday, May 30, 2020

React + React Native Basics in 2020-2021

I am writing new blog posts for technologies every year because they change, they evolve. JavaScript today is nothing like the JavaScript 10 years ago. Today's topic is React and React Native. This is a narrative style cheat sheet of React Basics. It is my hope to organize those concepts in a cohesive way. It will tell you how the concepts are connected, but to find out more, to dive deeper, it is important to seek out external tutorials and resources. 

React is the declarative way to create web components, as opposed to vanilla javascript uses imperative, step by step, line by line instructional programming. ReactDOM inserts React components and render them onto a web page. Babel translates JSX to JavaScript and HTML that the browser can understand. 

Vanilla JavaScript is imperative. React is declarative. Just say you want a behavior / element, it will be there. No need to tell the computer step by step what to do. If the data (state) changes, the view will change to reflect that. It's like having smart elements that just know what to do. 

Repeated elements (groups of HTML tags) are great candidates to break up and to be rewritten as components.

React is a library for building user interface. 

The most important concept in React is components. The functionality, codes are organized into components that become UI elements. Every custom react component uses the extends keyword to inherit from the React.Component class. 

Why JavaScript? It is a great time to learn modern JavaScript (ES6), you can now code both front end and back end (full stack) with JavaScript, even use it for Augmented Reality, Animation, interactivity, games, and machine learning (via Tensorflow.js). 

Post in progress, in construction. Updated daily.

Getting Started
If you want to start with a seed app, try the create-react-app
Provides basic seeding, basic scaffolding
All the javascript files are in the src folder.

Normal to see the node_module folder in all node and react apps. That's where the packages are installed. 

To get a quick start you can use CDN served React using unpackaged instead of npm install

Basic Node commands
Start the node app in command line
$ npm start

install the latest and greatest
npm install npm@latest -g

Launches the placeholder app in localhost:3000

Check versions
node -v
npm -v


Key Concepts in React:

Declarative program : opposite of imperative programming, where we specify step-by-step instruction, implementing behaviors in details. In declarative programming we tell React what we want back, like a component. HTML is a declarative, because we don't need to implement every detail just tell the browser to render a <div>.

JSX : 

JSX mix html and javascript together. Write html with javascript. Uses camel case like javascript. 

Most common way to create react element is not use createElement but using JSX
const element = <div className='container'>Hello World</div>
ReactDOM.render(element, rootElement)

React uses JavaScript to write HTML codes using JSX.
const my_html = <h1>Hello World</h1>
It is a combination of JavaScript and HTML, won't validate in vanilla JavaScript. 

JSX philosophy is perhaps for your code to resemble the web components, the declarative nature of html tags,less like pure javascript spaghetti code.

Browser engines don't support JSX and translating JSX to JavaScript that's why we need libraries like Babel to make that translation from JSX to JavaScript. There's a Babel playground where you can see the interpreter in action. Try translating JSX code into Js. 


Components:
Components are great for reusable code in react. Perhaps the most important concept. 

React components, building blocks of the virtual DOM.
Every component needs a render function because it needs to know how to render the component to web page. 
React components auto attach props. When we use it it also knows which props we are referring to. It knows we want to use it

Functional component is good for a simple quick function. 

The components codes are organized into the components folder in the src subdirectory. 

To be frank, a component is a block of reusable code. 

This inside the component refers to the component 

Declarative UI

React core concept

React components rely on data passed to be dynamic

When writing babel code use the script tag <script type="text/babel"></script> instead of the regular javascript tag. 

Functional components describe how UI should look based on states and properties 

When writing JSX, we may also see {} which surrounds JavaScript expressions {my javascript expression}. it cannot interpolate complex JavaScript logic such as control flow. But can handle expressions and ternary operators. JavaScript inside {} will be interpolated. 
{{}} is interpolated as an empty object. 
hyphen? todo

New component tag name needs to be capitalized. When inspect the type of object, the element will not show as a normal HTML tag such as a tag, but a special component, custom component, with custom tag name reusable using custom component. 

When initializing, component calls construct, super if any inheritance and yes generally it will, to enable the component, setState to give initial values to the state.

State management. Track state. 

react.createElement() API is different from the createElement API on document
textText becomes children
just specify the type of element and pass in property value pairs as an object
can also pass in children as an array
react for creating the elements
react dom for rendering elements to the page


Babel 

Babel is the javascript compiler
tryout playground available
compile JSX to vanilla javascript


is used to convert JSX code to JavaScript, which is understood by the browser. We use the script tag with text/babel as type to tell Babel this code needs to be compiled. Babel will insert a new script tag on the page in JavaScript that the browser Js engine can understand. 

Apparently the best practice is not to use Babel stand alone. 

Libraries:
React Core
    React core does not have the request module - one example why we need ReactDOM. 
ReactDOM : insert components into DOM. Takes components insert into DOM.
Babel : compatibility, helps convert JSX to JavaScript (Browsers can understand Js code, not JSX)
React Native : Build mobile apps using just JavaScript. Write once, deploy any where. Supports iOS and Android. Dependency is React. JavaScript is bundled, transpiled from ES7 ES6 ESNext down to ES5 code. Also minified (Source: CS50 Harvard). Multiple JavaScript files compiled into a one big JavaScript bundle. Separate threads for UI, layout, JavaScript (which is Single Thread and can get locked up). Prerequisite of React Native learning is to know core React concepts

Link to React, ReactDOM, and Babel using script tags in the headers.

Basic unit of react organized around components. It inherits from React.component. Usually contains a render function. 

class CappedComponentName extends React.component{
    render(){
        return <h1>Some HTML Code</h1>
    }
}

Props : objects that are passed to elements. It looks similar to JSON, but unlike JSON which can only handle strings, props can handle other JavaScript data types. 
React uses setState to change state props.

Arrow function: 
Benefit of using arrow function, is to handle the event variable and bind this correctly. this object can get kind of funky in js. 

Best practice:

A workaround best practice to ensure compatibility is to compile JSX to JavaScript before deployment. 

What is the different between props and states. States is something the component may want to track and modify. Props is somewhat like initialization, configuration, like states but with fewer changes

Use case:
    React can convert JSON data quickly to HTML
    React is really good for repetitive HTML, generating a lot of HTML templates repetitively which vary with data
    React components make coding easy
    React helps developer handles States
    React helps HTML page display data
    
Performance : 
    Virtual DOM computing and re-rendering with delta change only makes React performant, less expensive DOM rendering, refreshing, layout change with data.
    Virtual DOM manages delta update by monitoring changes and understand what constitutes a re-render, re-render partially, instead of regenerating DOM from scratch, which is costly and expensive

In general, front end development frameworks help reduce DOM manipulation work, and improves code quality 


Post in progress, in construction. Updated daily.

Components:
React components are independent, easy to maintain, reusable. Describe how components should look based on states, properties. state can be think of as a configuration


State:
In constructor we define the state of the component, what does the component needs to keep track of
this.state = {} property value pairs. state can be think of as a configuration

State is dynamic
State contains data that can change. In contrast with props. 

State is used on a class component not a functional component. 

Initial state vs changes of state

Styling React  | Make React App Pretty
Use React UI, Material UI
React UI includes cards, breadcrumbs, tree, accordian, 

Render function
Related concept : Virtual DOM
React Render function takes 2 arguments : element, target

For the return function to span multiple lines in render use ().
render(){

    return(
        <h1>

        </h1>
    )

}

We still need to call ReactDOM.render() and give it the location and component to render in order to display the UI on the page. 

-----

If data changes, in an eligible event, can trigger changes to all the components that use the data. 

----
React modules
import React from 'react'
that's the core react module. There is also a react module for react web (react-dom) and react native (mobile). Used to be one big app. 
Even have a module for VR. 
----

Files

App.js 
main top level component, 
a wrapper for the rest of the project. Point to other component code. 

App.css 
main css file, 
Can organize css for other components, 
one css file per component. 

App.test.js 
coveres teseting
index.css --> css for the index.html

.gitignore
is good for ignoring sensitive information, large uneccessary files such as node_modules, etc.  such as data files. 

package.json
not specific to react
 common in all node projects
 contain information about the app, such as author dependencies, such as react-dom, react-scripts (used by create-react-app)
package.json the file that describes the node project
also describes dependencies

npm install command will install these dependencies

---
Best practice: 

When removing a .js or .css file be sure to also remove any related import statements.

Divide a web app into logical components to organize, render and update with data. 

serviceworker for push notifications.
--
React modules
react core is used for creating elements
react dom is used for rendering the elements to the DOM

----
React createElement method creates an element using React instead of using the vanilla javascript. This element can used and manipulated using react easily.

Make your React app look pretty using React Bootstrap as a starter. Animate your app using React Spring. 
----
React Fragment
Can render elements side by side which is other wise not possible
Great for rendering tables which has a lot of tags side by side

short hand <></> is the functional equivalent of fragments in JSX

React Dev console
React UI Kit for rapid prototyping. React bootstrap. 

React Developer Tool

As of 2020, the react developer tool has 1283 plus reviews, and 2mm users in the chrome extension store!

React hook 

Introduced around 2019, a React function. Reusable function. 


1 comment:

  1. kellybags onlineshop
    If you want to buy gucci bags with good quality and low price, you can choose to buy them here kelly bag

    ReplyDelete

Coding for Good, Coding as a Service resources

 Did you know that being a developer you are at an unique position to help the society? There are many public service opportunities to contr...