Tuesday, September 21, 2021

React without JSX, with Hooks

React example "counter" app with CDN scripts only, no node.js server for transpiling JSX.
The transliling (conversion of JSX syntax to JavaScript function calls) is done in web browser.

<html>
<div id='app'></div>
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<script type="application/javascript" src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>
<script type="text/babel">
  const Count = () => { 
    const [count, setCount] = React.useState(0);
    return (
      <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>Click!</button>
      </div>
    );
  }
  ReactDOM.render(<Count />, document.getElementById('app'))
</script>
</html>


Next is the same example without using JSX at all, so no transpiling step an no babel script needed.
Instead, using React functions directly.

reactjs - Is it possible to use React Hooks API without using JSX (in typescript) - Stack Overflow

<html>
<div id='app'></div>
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<script>
const e = React.createElement;
const Count = () => {
   const [count, setCount] = React.useState(0);
   const button = e('button', {onClick: () => setCount(count+1)}, 'Click!');
   return e('div'null, e('p'null, `You clicked ${count} times`), button);
}
ReactDOM.render(e(Count), document.getElementById('app'));
</script>
</html>


while developing is is convenient to use React dev includes, that show descriptive messages

<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

React Without JSX – React

Introducing Hooks – React