Add React to a Website: Step 3: Create a React Component

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.

Related concepts

Step 3: Create a React Component

Add React to a Website: Step 3: Create a React Component — Structure map

Clickable & Draggable!

Add React to a Website: Step 3: Create a React Component — Related pages: