React Base Fiddle (JSX)
Starting point for creating JSFiddles with React.
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<h4>
Natural React component mount:
</h4>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<br>
<h4>
Web-Component React mount, with synthetic events:
</h4>
<react-synthetic-events ></react-synthetic-events>
<br>
<h4>
Web-Component React mount, with DOM events:
</h4>
<react-dom-events ></react-dom-events>
Babel + JSX
class CounterWithSyntheticEvents extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
};
}
handleClick() {
this.setState(prevState => ({ counter: prevState.counter + 1 }));
}
render() {
return (
<div>
Count {this.state.counter} <button onClick={this.handleClick.bind(this)}>+</button>
</div>
);
}
}
class CounterWithDOMEvents extends React.Component {
constructor(props) {
super(props);
this.buttonRef = React.createRef();
this.state = {
counter: 0,
};
}
componentDidMount() {
const listenerFn = this.handleClick.bind(this);
this.buttonRef.current.addEventListener("click", listenerFn);
this.removeListener = () => this.buttonRef.current.removeEventListener('click', listenerFn);
}
componentWillUnmount() {
this.removeListener();
}
handleClick() {
this.setState(prevState => ({ counter: prevState.counter + 1 }));
}
render() {
return (
<div>
Count {this.state.counter} <button ref={this.buttonRef}>+</button>
</div>
);
}
}
ReactDOM.render(<CounterWithSyntheticEvents />, document.getElementById("container"));
class ReactSyntheticEvents extends HTMLElement {
connectedCallback() {
const mountPoint = document.createElement("div");
const shadow = this.attachShadow({ mode: "open" });
shadow.appendChild(mountPoint);
ReactDOM.render(<CounterWithSyntheticEvents />, mountPoint);
}
}
customElements.define("react-synthetic-events", ReactSyntheticEvents);
class ReactDOMEvents extends HTMLElement {
connectedCallback() {
const mountPoint = document.createElement("div");
const shadow = this.attachShadow({ mode: "open" });
shadow.appendChild(mountPoint);
...