Skip to content

Instantly share code, notes, and snippets.

@cgarvis
Created December 16, 2014 17:57
Show Gist options
  • Save cgarvis/3ba440a724909689b9dc to your computer and use it in GitHub Desktop.
Save cgarvis/3ba440a724909689b9dc to your computer and use it in GitHub Desktop.
React Behaviors
var React = require('react');
var List = require('./list.js');
function registerBehavior(reactClass, selector) {
var mountingNodes = document.querySelectorAll(selector);
for(var i = 0; i< mountingNodes.length; i++) {
React.render(React.createElement(reactClass), mountingNodes[i]);
}
}
registerBehavior(List, '.js-list');
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
</head>
<body>
<div class="js-list"></div>
<div class="js-list"></div>
<script src="/app.js"></script>
</body>
</html>
var React = require('react');
var List = React.createClass({
getInitialState: function() {
return {
items: [
]
};
},
_addItem: function() {
var items = this.state.items;
items.push('Item #' + (items.length + 1));
this.setState({items: items});
},
render: function() {
var items = this.state.items;
return (
<div>
<ul>
{items.map(function(item) {
return <li>{item}</li>
})}
</ul>
<button className="btn btn-default" onClick={this._addItem}>Add item</button>
</div>
)
}
});
module.exports = List;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment