Skip to content

Instantly share code, notes, and snippets.

@aliakakis
Last active October 18, 2017 10:52
Show Gist options
  • Save aliakakis/0ed9f75714929e28e194045b9f6b9f8d to your computer and use it in GitHub Desktop.
Save aliakakis/0ed9f75714929e28e194045b9f6b9f8d to your computer and use it in GitHub Desktop.
React component that will redraw its children when there is a re-render thus resetting it
import React, {Component} from 'react';
import PropTypes from 'prop-types';
export default class Redraw extends Component {
constructor(props) {
super(props);
this.infoMessages = {
warning: 'You cannot use Redraw to return an array of children in v.15.x.x',
};
this.state = {
redrawState: true,
};
}
componentWillMount() {
const { children } = this.props;
const { warning } = this.infoMessages;
if (children instanceof Array) {
throw new SyntaxError(warning);
}
}
componentWillReceiveProps() {
this.redrawElement(false);
}
shouldComponentUpdate(nextProps, nextState) {
const { redrawState } = this.state;
if (nextState.redrawState === redrawState) {
return false;
}
return true;
}
componentDidUpdate() {
this.redrawElement(true);
}
redrawElement = (force) => {
this.setState({
redrawState: force,
});
};
render() {
const { children } = this.props;
const { redrawState } = this.state;
return (
redrawState && children
);
}
}
Redraw.defaultProps = {
backup: false,
};
Redraw.propTypes = {
backup: PropTypes.bool,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment