MENU
Adding React directly in HTML
Addingthree files (and your component .js file(s)) to your HTML file allows you to quickly use React:
RESETRUNFULL
<!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>
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". --> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<!-- Load our React component LAST. -->
<script src="like_button.js" type="text/babel"></script>
</body></html>
// 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 (
/* JSX code following… */
<button onClick={() => this.setState({ liked: true })}>
Like
</button>
);
}}const domContainer = document.querySelector('#like_button_container');ReactDOM.render(e(LikeButton), domContainer);
After you have finalized your source codes, to build an optimized webpage for your site visitors, you should be using the production-ready files:
RESETRUNFULL
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js" ></script><script crossorigin
src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" ></script>
and compile the JSX code using Babel:
npm install babel-cli babel-preset-react-appnpx babel --watch *.js --out-dir build --presets react-app/prod |
Any JSX code will be instantly converted to browser-compatible JS codes as you save the files.
You won't need to explicitly import React as is the case for Create-React-App(1.2):
RESETRUNFULL
import React, { Component } from 'react'; // already imported in prior <script>…</script>
To do away with the boilerplate 'React.', you can assign a member manually:
RESETRUNFULL
const Component = React.Component;