React Installation (CDN)
React can be downloaded and used directly; the download package also provides many learning examples.
This tutorial uses React version 18.2.0. You can visit the official websitehttps://reactjs.org/to download the latest version.
Use ByteDance's React CDN library, with the address as follows:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js" ></script>
Use Staticfile CDN's React CDN library, with the address as follows:
The CDN address provided by the official website:
Note:Using Babel to compile JSX in the browser is very inefficient.
Usage Example
The following example outputs Hello, React!
React Example
Try it Yourself »
Example analysis:
In the example, we introduced three libraries: react.production.min.js, react-dom.production.min.js, and babel.min.js:
- react.min.js- React core library
- react-dom.min.js- Provides DOM-related functionality
- babel.min.js- Babel can convert ES6 code to ES5 code, so we can run React code on browsers that currently do not support ES6. Babel has built-in support for JSX. By using Babel together with the babel-sublime package, you can take source code syntax highlighting to a whole new level.
The above code inserts an h1 heading into the node with id="example".
const root = ReactDOM.createRoot(document.getElementById("example"));
- Get the DOM container:
document.getElementById("example")It gets a DOM element with id "example". - Create a root node:
ReactDOM.createRootIt is a new method introduced in React 18, used to create a React root node. In this example,rootthe variable stores this root node.
Other ExtensionsNote:
If we need to use JSX, the type attribute of the <script> tag needs to be set to text/babel.