Skip to content

Instantly share code, notes, and snippets.

@bradennapier
Last active October 1, 2017 23:17
Show Gist options
  • Save bradennapier/5a61c77318b075cf0e4bc207c40faba8 to your computer and use it in GitHub Desktop.
Save bradennapier/5a61c77318b075cf0e4bc207c40faba8 to your computer and use it in GitHub Desktop.
const REACT_PROTOTYPE = [
'constructor',
'autobind',
'childContextTypes',
'componentDidMount',
'componentDidUpdate',
'componentWillMount',
'componentDidCatch',
'componentWillReceiveProps',
'componentWillUnmount',
'componentWillUpdate',
'contextTypes',
'displayName',
'forceUpdate',
'getChildContext',
'getDefaultProps',
'getDOMNode',
'getInitialState',
'isMounted',
'mixins',
'propTypes',
'render',
'props',
'state',
'replaceProps',
'setProps',
'setState',
'shouldComponentUpdate',
'statics',
'updateComponent',
'isReactComponent',
'forceUpdate',
'replaceState',
];
export default function hoistNonReactMethods(srcKey, dest) {
const src = dest[srcKey];
for (const key of Object.keys(src)) {
const val = src[key];
let targetName = key;
if (process.env.NODE_ENV === 'development') {
if (key.startsWith('__') && key.endsWith('__REACT_HOT_LOADER__')) {
targetName = key.replace('__', '');
targetName = targetName.replace('__REACT_HOT_LOADER__', '');
}
}
if (
typeof val === 'function' &&
!REACT_PROTOTYPE.includes(val) &&
!targetName.startsWith('_')
) {
if (dest[targetName]) {
if (process.env.NODE_ENV === 'development') {
console.warn(
`[hoistNonReactMethods] ${targetName} exists in destination and will not be copied`,
);
}
continue;
}
dest[targetName] = function hoistedMethodProxy(...args) {
const currentSource = dest[srcKey];
return currentSource[key].call(currentSource, ...args);
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment