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:
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>
Few points to note
-
Instead of
React.createElement("div",...
we are using React factory methodReact.DOM.div
. It helps improve code readability. - 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.
-
We pass count 3 to MyList (
{count: "3"}
) which can be accessed using this.props.count. - getInitialState is used to get initial state. It looks for props passed to component. If nothing passed, then it uses default values.
- render is called initially and whenever state is changed.
- We attached a click handler on button “click to add”. The handler changes the state and increments the count.
- Since changes are done in virtual dom and then applied in real dom. It help reduce browser reflow and repaint and makes rendering fast.