Why React
is so popular at the moment?
-
- Composition: it combines easy functions to create complex functions.
-
- Declarative (Not imperative): you tell JS what you want to do. It takes care of the steps itself, without you worrying about it.
-
- Unidirectional data flow The data flows through a component in one direction only (Not 2 way data binding). => from parent to children NOTE: the data update ONLY occurs in parent component.
-
- React is just JavaScript.
The Virtual DOM
= a tree in which each node is an HTML element.
- React is able to traverse and carry out operations on this Virtual DOM,
- saving our app from having "costly" activity on the actual DOM. Virtual DOM
Diffing
= to make efficient changes to the DOM.
- With diffing, old DOM nodes are taken out and replaced only when necessary.
- This way, our app doesn't perform any unnecessary operations to figure out when to render content. Diffing Algorithm
Normally, when you code, the render process will both "Decide what data to render" & "Render the data" at the same time.
In React this process is decoupled: Render component onto root div ReactDOM takes 2 arguments:
-
- What data to render (=React component)
-
- Where to render the data (=DOM element) NOTE: ReactDom is used, because we work in the browser.
This makes it possible to RENDER on:
- native devices.
- server.
- VR environments.
EXAMPLE - index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</p>
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>
EXAMPLE - like_button.js
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
There are three ways to install REACT:
- REACT COMPONENT (see above) REACT COMPONENTS-Add React to a website
- REACT WITH JSX (BABEL NEEDED) New App Existing App
- REACT WITHOUT JSX (__NO__BABEL NEEDED) REACT withouth jsx REACT cdn links