React component tutorial with click handler – javascript version

This tutorial is javascript version is React component tuorial with click handler – jsx version. It is recommended that you visit that tutorial before reading this. Even though JSX is easier to read, it is still a good idea to be familiar with corresponding javascript syntax. It can also help in Javascript debugging in Chrome.

Here is the screenshot of final outcome:
react-component-with-click-handler-example-javascript-version

Basic React component with props and click handler – javascript version

Here is the html and javascript code (withou jsx) used in this tutorial and how it renders:

<script src="https://fb.me/react-0.14.7.js"></script>
<script src="https://fb.me/react-dom-0.14.7.js"></script>
<div id="mylist"></div>

<script type="text/javascript">
var MyList = React.createClass({
  getInitialState: function () {
    return {count: parseInt(this.props.count || "2") };
  },
  handleClick: function (event) {
    this.setState({count: this.state.count + 1});
  },
  render: function () {
    var count = this.state.count;
    return React.DOM.div(
      null,
      "total items: ",
      count,
      React.DOM.ul(
        null,
        Array(count).join().split(",").map((x, i) => React.DOM.li(
          {key: i}, "item ", i
        ))
      ),
      React.DOM.button(
        {onClick: this.handleClick}, "click to add"
      )
    );
  }
});
ReactDOM.render(React.createElement(MyList, {count: "3"}), document.getElementById('mylist'));
</script>
refresh

Few points to note

  1. Instead of React.createElement("div",... we are using React factory method React.DOM.div. It helps improve code readability.
  2. 1st argument to React.DOM.div is properties and 2nd and subsequent arguments to React.DOM.div are taken as content of that div element.
  3. We pass count 3 to MyList ({count: "3"}) which can be accessed using this.props.count.
  4. getInitialState is used to get initial state. It looks for props passed to component. If nothing passed, then it uses default values.
  5. render is called initially and whenever state is changed.
  6. We attached a click handler on button “click to add”. The handler changes the state and increments the count.
  7. Since changes are done in virtual dom and then applied in real dom. It help reduce browser reflow and repaint and makes rendering fast.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments