<!-- ... existing HTML ... --> <div id="like_button_container"></div> <!-- ... existing HTML ... -->
<body> <!-- ... other HTML ... --> <!-- Load React. --> <!-- Note: when deploying, replace "development.js" with "production.min.js". --> <script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script> <!-- Load our React component. --> <script src="like_button.js"></script> </body>
like_button.js
.
This code defines a React component called ‘LikeButton’.
'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' ); } }
like_button.js
. These two
lines of code find the <div> we added to our HTML in the first step, and
then display our “Like” button React component inside of it.
// ... the starter code you pasted ... const domContainer = document.querySelector('#like_button_container'); ReactDOM.render(e(LikeButton), domContainer);
You have just added the first React component to your website.
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
Now you can use JSX in any ‘<script>’ tag by adding type="text/babel"
attribute to it. Change the "Like" button code as follows:
// const e = React.createElement; // // Display a "Like" <button> // return e( // 'button', // { onClick: () => this.setState({ liked: true }) }, // 'Like' // ); // Display a "Like" <button> return ( <button onClick={() => this.setState({ liked: true })}> Like </button> );
These two code snippets are equivalent. JSX is completely optional.