UPD Convert Angular and Backbone views as well with MVC elements project
Placing component in a pure HTML
<body>
<my-react-component items="{window.someArray}"></my-react-component>
</body>
React class definition
/* @jsx React.DOM */
MyComponent = React.createClass({
render: function() {
console.log(this.props.items); // passed as HTML tag`s argument
console.log(this.props.children); // original tag children
return <ul><li>React content</li></ul>;
}
});
document.registerReact('my-react-component', MyComponent);
Find demo in corresponding folder.
Original children of a custom element is injected to component as this.props.children
.
<my-react-component>Hello world</my-react-component>
In this case props.children is equal to "Hello world".
Container node of the element is passed as this.props.container
. Both props.container and props.children have type of documentFragment
.
If you want to expose React component methods on custom element - assign them to component as following:
componentDidMount: function() {
this.props.container.setTextContent = this.setTextContent.bind(this);
...
You may add attributeChanged
callback to component in order to handle / modify / filter incoming values.
attributeChanged: function(attributeName, oldValue, newValue) {
console.log('Attribute ' + attributeName + ' was changed from ' + oldValue + ' to ' + newValue);
this.props[attributeName] = parseInt(newValue);
}
You may trigger DOM event from React component by using following snippet:
var event = new CustomEvent('change', {
bubbles: true
});
React.findDOMNode(this).dispatchEvent(event)
Subscribing to DOM events is similar:
React.findDOMNode(this).addEventListener('change', function(e){...});
- NPM: reactive-elements
- Bower: ReactiveElements
Polyfill binds to DOMContentLoaded
in order to process DOM so no custom elements exist until it fired. To prevent this hook into DOMContentLoaded
and operate elements on it or after.
Copyright 2014 Denis Radin aka PixelsCommander
Inspired by Christopher Chedeau`s react-xtags