React is an enhancement to the UI management. Traditional UI operations (DOM APIs) will need to work on too many details, whereas React applies a global refreshing to facilitate their management. React also helps to scale and maintain the application program status which can be distributed everywhere.
Environment
- macOS Catalina, Version 10.15.7.
Install React
Create a directory (e.g., hello
) and install two packages as below:
npm i react
installs the core of React which allows to create elements, components, and etc.npm i react-dom
provides the support for DOM.
Hello, World!
Add a new index.html
page to the root of hello
.
Under VS Code, a new HTML page can be quickly created by typing doc
+ tab
key, which should then give a basic framework of HTML pages:
<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>
</head>
<body>
</body>
</html>
Then follow the below steps to add and render a React element to the body tag.
-
Import the JavaScript files of react packages.
<script src="./node_modules/react/umd/react.development.js"></script> <script src="./node_modules/react-dom/umd/react-dom.development.js"></script>
-
Create a React element.
const title = React.createElement('h1', null, 'Hello, World!')
'h1'
tells the name of the element.null
is the attribute of the element.'Hello, World!'
is the content of the element.
-
Render the React element.
ReactDOM.render(title, document.getElementById('root'))
title
is the React element to render.document.getElementById('root')
indicates the mount point (this requires to add<div id="root"></div>
to the body tag first).
The final code of the body tag then becomes:
<body>
<div id="root"></div>
<script src="./node_modules/react/umd/react.development.js"></script>
<script src="./node_modules/react-dom/umd/react-dom.development.js"></script>
<script>
const title = React.createElement('h1', null, 'Hello, World!')
ReactDOM.render(title, document.getElementById('root'))
</script>
</body>
Use JSX
It will become tedious and less intuitive to create elements via createElement
when the page structure becomes more and more complex.
The recommended way is to use JSX (JavaScript XML) which is similar to HTML.
For example, we can simply write:
const title = <h1>Hello, World!</h1>
Use create-react-app
$ npx create-react-app hello
Then edit index.js
as below.
Note that now we can import the react
and react-dom
packages instead of
using JavaScript labels.
import React from 'react';
import ReactDOM from 'react-dom';
const title = (<h1>Hello, World!</h1>)
ReactDOM.render(title, document.getElementById('root'))
To start this app with a specified port, run
$ PORT=3001 npm start
Note that in order to access this page from the host machine, both host and
guest IPs need to use the value from the inet
address (via ifconfig
)
respectively.