MENU
Adding React directly in HTML
Adding three files (and your component .js file(s)) to your HTML file allows you to quickly use React:
RESETRUNFULL
'use strict';
const e = React.createElement;
function LikeButton() {
const [liked, setLiked] = React.useState(false);
if (liked) {
return 'You liked this.';
}
return (
/* JSX code following… */
<button onClick={() => setLiked(true)}>
Like
</button>
);
}
const domContainer = document.querySelector('#like_button_container');
const root = ReactDOM.createRoot(domContainer);
root.render(e(LikeButton));<!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@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/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>After you have finalized your source codes, to build an optimized webpage for your site visitors, you should be using the production-ready files:
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/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:
import React, { Component } from 'react'; // already imported in prior <script>…</script>To do away with the boilerplate 'React.', you can assign a member manually:
const Component = React.Component;