JSFiddle - React, Tailwind, and code Playground
by Jason Miller
HTML
<script src="https://npmcdn.com/preact@beta"></script>
CSS
body {
padding: 10px;
}
foo {
display: block;
position: relative;
border: 1px solid #CCC;
margin: 5px 15px;
padding: 5px;
}
.renders {
position: absolute;
right: 0;
top: 0;
padding: 2px 5px;
font-size: 10px;
background: #CCC;
color: #FFF;
border-radius: 0 0 0 3px;
}
Babel + JSX
let { h, Component, render } = preact; /** @jsx h */
class Foo extends Component {
renders = 0;
shouldComponentUpdate() {
return false;
}
render({ children, ...props }) {
return (
<foo {...props}>
<span class="renders">{++this.renders}</span>
{children || 'shouldComponentUpdate():false'}
</foo>
);
}
}
class Demo extends Component {
render() {
return (
<div>
<button onClick={ () => deepForceUpdate(this) }>deepForceUpdate()</button>
<Foo>
<Foo />
<Foo>
<div>
<Foo />
<Foo />
<Foo />
</div>
</Foo>
<Foo />
<Foo />
</Foo>
</div>
);
}
}
render(<Demo />, document.body);
// SOURCE: https://gist.github.com/developit/8b31e8144d06bf30a780aa1216722acb
/** Invoke `.forceUpdate()` on a component and all descendants. */
function deepForceUpdate(component) {
component.forceUpdate();
// high-order child recursion
if (component._component) {
deepForceUpdate(component._component);
}
else if (component.base) {
updateComponentsFromDom(component.base);
}
}
function updateComponentsFromDom(node, fn) {
let children = node.childNodes;
for (let i=children && children.length; i--; ) {
let child = children[i];
if (child._component) {
deepForceUpdate(child._component);
}
else {
updateComponentsFromDom(child, fn);
}
}
}