React became popular because of its rapid DOM rendering speed. A Web page is made up of the structure of HTML elements. It creates a tree for all nodes, but reading and writing the DOM is slow. React JS uses the concept of a virtual DOM to make it faster.
The virtual DOM of React JS
Normally, when the DOM is updated, the rendering of the page takes place.
Downloading the starter kit
Alternatively, we can use the script tag in our HTML file to link to React as shown in the following code:
<script src=https://fb.me/react-0.14.8.min.js></script> <script src=https://fb.me/react-dom-0.14.8.min.js></script>
For this article, we will follow the latter approach.
A sample application
Open the HTML file in a browser; it will display Hello World as shown in Figure 5.
The basic example is very simple, but when updating many elements on pages or adding elements, the created elements will be difficult to maintain. React allows you to create reusable components using JSX.
Let us modify the above example to make it a component and use JSX instead of createElement. We will create a class which will have the render function. We will store it in a variable HelloWorld, making it a component that can be used later in React.render. Figure 6 shows the new updated code with JSX.
The output is shown in Figure 7.
Lets now add the properties to our components. Properties are nothing but attributes to an HTML. In the React class, these can be accessed using this.props, and a change in properties will render the component again. Let us add the property uname to display Hello followed by uname. Figure 8 shows the modified code.
Refresh the browser, or open the modified file in a browser. This will display Hello followed by a name as shown in Figure 9.
For this application, we need the following three components:
- Form for input: AddItem component
- List to display data: DisplayList component
- Main component to hold the above two: AppMain component
The output of the application is shown in Figure 10.
The code for AddItem is shown in Figure 11, DisplayList is shown in Figure 12 and AppMain is shown in Figure 13.
This is a simple demo of how to use React JS. For more details, refer to the online documentation at https://facebook.github.io/react/docs/getting-started.html. More examples can also be found if you download the starter kit from the download page.