Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React and Web Component ()
function getEventTarget(nativeEvent) {
var target = nativeEvent.target || nativeEvent.srcElement || window;
// If encapsulated in a Web Component
// use the Event path
if(nativeEvent.path && nativeEvent.path[0]) {
return nativeEvent.path[0];
}
// Normalize SVG <use> element events #4963
if (target.correspondingUseElement) {
target = target.correspondingUseElement;
}
// Safari may fire events on text nodes (Node.TEXT_NODE is 3).
// @see http://www.quirksmode.org/js/events_properties.html
return target.nodeType === 3 ? target.parentNode : target;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Basic Example with WebComponents</title>
<link rel="stylesheet" href="../shared/css/base.css" />
</head>
<body>
<h1>Basic Example with WebComponents</h1>
<div id="container">
<p>
To install React, follow the instructions on
<a href="http://www.github.com/facebook/react/">GitHub</a>.
</p>
<p>
If you can see this, React is <strong>not</strong> working right.
If you checked out the source from GitHub make sure to run <code>grunt</code>.
</p>
</div>
<br /><br />
<h4>Example Details</h4>
<p>
This example demonstrates WebComponent/ReactComponent interoperability
by rendering a ReactComponent, which renders a WebComponent, which renders
another ReactComponent in the WebComponent's shadow DOM.
<p>
<p>
Learn more about React at
<a href="http://facebook.github.io/react" target="_blank">facebook.github.io/react</a>.
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.21/webcomponents.js"></script>
<script src="../../build/react.js"></script>
<script src="../../build/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
<script type="text/babel">
function exampleEventHandler(e) {
console.log('Hello', e);
}
// Define WebComponent
var proto = Object.create(HTMLElement.prototype, {
attachedCallback: {
value: function() {
var mountPoint = document.createElement('span');
this.createShadowRoot().appendChild(mountPoint);
var name = this.getAttribute('name');
ReactDOM.render(<button onClick={exampleEventHandler}>{name}</button>, mountPoint);
}
}
});
document.registerElement('x-search', {prototype: proto});
// Define React Component
class HelloMessage extends React.Component {
render() {
return <div>Hello <x-search name={this.props.name} />!</div>;
}
}
// Mount React Component (which uses WebComponent which uses React)
var container = document.getElementById('container');
ReactDOM.render(<HelloMessage name="Jim Sproch" />, container);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.