Skip to content

Commit

Permalink
Fix lifecycle method usages in Modal
Browse files Browse the repository at this point in the history
  • Loading branch information
Hypnosphi authored and diasbruno committed Apr 13, 2018
1 parent 0dd7805 commit e91d59a
Showing 1 changed file with 18 additions and 34 deletions.
52 changes: 18 additions & 34 deletions src/components/Modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@ const createPortal = isReact16
: ReactDOM.unstable_renderSubtreeIntoContainer;

function getParentElement(parentSelector) {
return parentSelector() || Modal.defaultProps.parentSelector;
return parentSelector();
}

class Modal extends Component {
state = Object.assign({}, Modal.defaultProps);

static setAppElement(element) {
ariaAppHider.setElement(element);
}
Expand Down Expand Up @@ -122,45 +120,31 @@ class Modal extends Component {
!isReact16 && this.renderPortal(this.props);
}

static getDerivedStateFromProps(newProps, prevState) {
if (!canUseDOM) return null;
const { isOpen } = newProps;
// Stop unnecessary renders if modal is remaining closed
if (prevState && !prevState.isOpen && !isOpen) return null;

const currentParent = getParentElement(prevState.parentSelector);
const newParent = getParentElement(newProps.parentSelector);
getSnapshotBeforeUpdate(prevProps) {
const prevParent = getParentElement(prevProps.parentSelector);
const nextParent = getParentElement(this.props.parentSelector);
return { prevParent, nextParent };
}

const enumeratedState = {
isOpen: newProps.isOpen,
parentSelector: newProps.parentSelector,
portalClassName: newProps.portalClassName
};
componentDidUpdate(prevProps, _, snapshot) {
if (!canUseDOM) return;
const { isOpen, portalClassName } = this.props;

if (newParent !== currentParent) {
currentParent.removeChild(this.node);
newParent.appendChild(this.node);
if (prevProps.portalClassName !== portalClassName) {
this.node.className = portalClassName;
}

const newState = Object.assign(prevState, enumeratedState);
!isReact16 && this.renderPortal(newProps);
return newState;
}
// Stop unnecessary renders if modal is remaining closed
if (!prevProps.isOpen && !isOpen) return;

getSnapshotBeforeUpdate(prevProps, prevState) {
if (!canUseDOM) {
return null;
} else {
this.node.className = prevState.portalClassName;
return prevState.portalClassName;
const { prevParent, nextParent } = snapshot;
if (nextParent !== prevParent) {
prevParent.removeChild(this.node);
nextParent.appendChild(this.node);
}
}

/*eslint-disable no-unused-vars*/
componentDidUpdate(prevProps, prevState) {
// Just to satisfy polyfilling
!isReact16 && this.renderPortal(this.props);
}
/*eslint-enable no-unused-vars*/

componentWillUnmount() {
if (!canUseDOM || !this.node || !this.portal) return;
Expand Down

0 comments on commit e91d59a

Please sign in to comment.