Skip to content

useState and useHooks in HTML

first of all, I can not use the “create-react-app” command in the current project.

so here I am trying to add my react code into a plain HTML file.

Here are my codes for HTML and js files.

can anyone tell me why my hooks and setState don’t work properly?

Please guide me to solve it.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
  </head>
  <body>

    <p>React is loaded as a script tag.</p>

    <!-- We will put our React component inside this div. -->
    <div id="like_button_container"></div>

    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

    <!-- Load our React component. -->
    <script src="like_button.js"></script>

  </body>
</html>

my like_button.js codes

'use strict';

const e = React.createElement;

const LikeButton = () => {
  const [liked, setLiked] = useState(false);

  useEffect(() => {
    if (liked) {
      return <div>You liked this</div>;
    }
  }, [liked]);

  return e('button', { onClick: () => setLiked(true) }, 'Like');
};

const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);

Answer

Your trying to return from a useEffect, the return from a useEffect is for cleanUp of an effect,.

In fact you don’t even require to use useEffect, you just need to change your render based on your liked state.

Also your example code you showed has JSX syntax, so not sure why your using createElement but I’ve created the example below without it, just in case..

eg.

const e = React.createElement;

const {useState, useEffect} = React;

const LikeButton = () => {
  const [liked, setLiked] = useState(false);
  return e('button', { onClick: () => setLiked(true) },   
    liked ? 'You Like this..' : 'Like');
};

const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>