React: Add React to a Website

Add React to a Website

Step 1: Add a DOM Container to the HTML

<!-- ... existing HTML ... -->

<div id="like_button_container"></div>

<!-- ... existing HTML ... -->

Open the HTML page you want to edit. Add an empty div tag to mark the spot where you want to display something with React.

Step 2: Add the Script Tags

<!-- ... other HTML ... -->

  <!-- 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>

Add three 'script' tags to the HTML page right before the closing '/body' tag.

Step 3: Create a React Component

'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 e(
      'button',
      { onClick: () => this.setState({ liked: true }) },
      'Like'
    );
  }
}

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

Create a file called like_button.js next to your HTML page. Paste demo code into the file you created. The last two lines of code find the <div> we added to our HTML in the first step, and then display our “Like” button component inside of it.

React: Add React to a Website — Structure map

Clickable & Draggable!

React: Add React to a Website — Related pages: