How I learnt to think in React!
Concepts you should understand before you start React components.
Table of contents
Concepts you should understand before you start React components.
01- Building a static web page using CDNs development files and Babel at index.html
π react-dom library gives us access to the global variable ReactDOM.
π Babel enables us to write JSX directly in our index.js file.
Don't forget to add type="text/babel" to your script to enable Babel.
index.js file
ReactDOM.render(<h1>My 1st React Code!</h1>, document.getElementById('root'));
// ReactDOM.render(what, where) used to render something to the screen.
What React element to be rendered on the screen.
Where: index.html inside a real DOM element
// Acts as a container for the entire React app/website.
<div id="root"></div>
index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script
crossorigin
src="https://unpkg.com/react@17/umd/react.development.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"
></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<!-- Utilizing Babel in writing JSX directly in our index.js file -->
<script src="index.js" type="text/babel"></script>
</body>
</html>
02-Why React
React is Composable
π React allows us to write composable code through custom components that hold a piece of our UI allowing us to write a code that is easy to maintain.
React is Declarative
π Declarative means I can tell the computer WHAT to do and expect it to handle the details.
Ex: writing JSX code instead of plain JavaScript.
π Imperative means I need to tell it HOW to do each step.
03-JSX: "JavaScript XML"
The object-nature of React elements
π JSX provides a declarative approach over the regular vanilla JavaScript code.
04- π₯Bonusπ₯ The difference between JSX and regular DOM
// Vanilla JavaScript code:
const h1 = document.createElement('h1');
h1.textContent = 'My 1st React Code!';
h1.className = 'main-header';
console.log(h1); // Real DOM element: <h1 class="main-header">
// Declarative JSX code:
const h1 = <h1 className="main-header">My 1st React Code!</h1>
console.log(h1); // Plain JS object
{
type: 'h1',
key: null,
ref: null,
props: {
className: 'main-header',
children: 'My 1st React Code!',
},
_owner: null,
_store: {},
}
π JSX returns a plain old JS object.
A string representation of the regular JS object returned by JSX.
π Only React takes these kind of objects and turns them into real DOM element that the browser can interpret.
// The plain JS object returned by JSX isn't recognized by the browser!
// html.append(element); //// [object Object]
// html.append(JSON.stringify(element)); //// Show it in details
ReactDOM.render(element, document.getElementById('root'));