Using react.js and react-dom.js in an HTML Page

The react.js file is the core file needed to create React elements and write react components. When you intend to render your components in an HTML document (i.e., the DOM) you’ll also need the react-dom.js file. The react-dom.js file is dependent on the react.js file and must be included after first including the react.js file.

An example of an HTML document properly including React is shown below.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script src="https://fb.me/react-15.2.0.js"></script>
  5. <script src="https://fb.me/react-dom-15.2.0.js"></script>
  6. </head>
  7. <body>
  8. </body>
  9. </html>

With the react.js file and react-dom.js file loaded into an HTML page it is then possible to create React nodes/components and then render them to the DOM. In the HTML below a HelloMessage React component is created containing a React <div> node that is rendered to the DOM inside of the <div id="app"></div> HTML element.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script src="https://fb.me/react-15.2.0.js"></script>
  5. <script src="https://fb.me/react-dom-15.2.0.js"></script>
  6. </head>
  7. <body>
  8. <div id="app"></div>
  9. <script>
  10. var HelloMessage = React.createClass({
  11. displayName: 'HelloMessage',
  12. render: function render() {
  13. return React.createElement('div',null,'Hello ',this.props.name);
  14. }
  15. });
  16. ReactDOM.render(React.createElement(HelloMessage,{ name: 'John' }), document.getElementById('app'));
  17. </script>
  18. </body>
  19. </html>

This setup is all you need to use React. However this setup does not make use of JSX. The next section will discuss JSX usage.

Notes

  • An alternative react.js file called react-with-addons.js is available containing a collection of utility modules for building React applications. The “addons” file can be used in place of the react.js file.
  • Don’t make the <body> element the root node for your React app. Always put a root <div> into <body>, give it an ID, and render into it. This gives React its own pool to play in without worrying about what else potentially wants to make changes to the children of the <body> element.