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.

<!DOCTYPE html>
<html>
  <head>
    <script src="https://fb.me/react-15.2.0.js"></script>
    <script src="https://fb.me/react-dom-15.2.0.js"></script>
  </head>
<body>
</body>
</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.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://fb.me/react-15.2.0.js"></script>
        <script src="https://fb.me/react-dom-15.2.0.js"></script>
    </head>
<body>
    <div id="app"></div>
    <script>
        var HelloMessage = React.createClass({
            displayName: 'HelloMessage',
            render: function render() {
                return React.createElement('div',null,'Hello ',this.props.name);
            }
        });
        ReactDOM.render(React.createElement(HelloMessage,{ name: 'John' }), document.getElementById('app'));
    </script>
</body>
</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.

results matching ""

    No results matching ""