Skip to content

Instantly share code, notes, and snippets.

@jossmac
Last active April 17, 2018 09:04
Show Gist options
  • Save jossmac/2b3a4dbc75da0045c82315b844f021c8 to your computer and use it in GitHub Desktop.
Save jossmac/2b3a4dbc75da0045c82315b844f021c8 to your computer and use it in GitHub Desktop.
React helper component for toggling styles and attributes
// @flow
import React, { PureComponent } from 'react';
type ObjectType = { [key: string]: string };
type Keys = Array<string>;
type Props = {
attributes: ObjectType,
styles: ObjectType,
target: HTMLElement,
};
class PropertyToggle extends PureComponent<Props> {
originalAttributes: ObjectType = {};
originalStyles: ObjectType = {};
attributeKeys: Keys;
styleKeys: Keys;
componentDidMount() {
const { attributes, styles, target } = this.props;
this.attributeKeys = Object.keys(attributes);
this.styleKeys = Object.keys(styles);
// styles
if (this.styleKeys.length) {
this.styleKeys.forEach(k => {
this.originalStyles[k] = target.style.getPropertyValue(k);
target.style.setProperty(k, styles[k]);
});
}
// attributes
if (this.attributeKeys.length) {
this.attributeKeys.forEach(k => {
this.originalAttributes[k] = target.getAttribute(k) || '';
target.setAttribute(k, attributes[k]);
});
}
}
componentWillUnmount() {
const { target } = this.props;
// styles
if (this.styleKeys.length) {
this.styleKeys.forEach(k => {
target.style.setProperty(k, this.originalStyles[k]);
});
}
// attributes
if (this.attributeKeys.length) {
this.attributeKeys.forEach(k => {
if (this.originalAttributes[k]) {
target.setAttribute(k, this.originalAttributes[k]);
} else {
target.removeAttribute(k);
}
});
}
}
render() {
return null;
}
}
type EnforcerProps = { isActive: boolean };
const LifeCycleEnforcer = ({ isActive, ...props }: Props & EnforcerProps) =>
isActive ? <PropertyToggle {...props} /> : null;
// appease flow
const defaultTarget = ((document.body: any): HTMLElement);
LifeCycleEnforcer.defaultProps = {
attributes: {},
target: defaultTarget,
styles: {},
};
export default LifeCycleEnforcer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment