Skip to content

Instantly share code, notes, and snippets.

@mohayonao
Created October 26, 2016 05:45
Show Gist options
  • Select an option

  • Save mohayonao/b9971996acef70755151d9926700be8b to your computer and use it in GitHub Desktop.

Select an option

Save mohayonao/b9971996acef70755151d9926700be8b to your computer and use it in GitHub Desktop.
import React, { Component, PropTypes } from "react";
import Volatile from "./Volatile";
@Volatile({ timeout: 2500 })
class UI extends Component {
static propTypes = {
data: PropTypes.number.isRequired,
};
shouldComponentUpdate(nextProps) {
return nextProps.data !== this.props.data;
}
rener() {
return (<div>{ this.props.data }</div>);
}
}
import React from "react";
export default function Volatile(opts = { timeout: 1000 }) {
return (Component) => {
return class VolatileComponent extends React.Component {
constructor(props) {
super(...props);
this.state = { visible: false };
this._timerId = 0;
}
componentWillReceiveProps(nextProps) {
if (this::Component.prototype.shouldComponentUpdate(nextProps)) { // <- !!?!?!?!???!?
this.setState({ visible: true });
clearTimeout(this._timerId);
this._timerId = setTimeout(() => {
this.setState({ visible: false });
}, opts.timeout);
}
}
shouldComponentUpdate(_, nextState) {
return nextState.visible || (nextState.visible !== this.state.visible);
}
render() {
if (!this.state.visible) {
return null;
}
return (<Component { ...this.props }/>);
}
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment