Skip to content

Instantly share code, notes, and snippets.

@slorber
Created April 23, 2018 15:30
Show Gist options
  • Save slorber/d473b9217b54427f3dec128bf08e14a2 to your computer and use it in GitHub Desktop.
Save slorber/d473b9217b54427f3dec128bf08e14a2 to your computer and use it in GitHub Desktop.
Lazy react native comp
import React from 'react';
import {InteractionManager, ActivityIndicator} from 'react-native';
import {View} from 'glamorous-native';
const DefaultLoader = (
<View padding={20} alignItems="center" justifyContent="center">
<ActivityIndicator size="large"/>
</View>
);
/*
This component is particularly useful to delay slightly the rendering of computation-heavy content
This permits to give an earlier feedback to user, and avoid triggering too much computation during animations
*/
export default class Lazy extends React.Component {
static defaultProps = {
disabled: false,
delay: 0,
loader: DefaultLoader,
children: null,
runAfterInteractions: false,
noLoader: false,
};
state = {
render: false,
};
componentDidMount() {
setTimeout(this.triggerRender, this.props.delay);
}
componentWillUnmount() {
this.unmounted = true;
}
doRender = () => {
if (!this.unmounted) {
this.setState({render: true});
}
};
triggerRender = () => {
this.props.runAfterInteractions ?
InteractionManager.runAfterInteractions(this.doRender)
: this.doRender();
};
render() {
if (this.props.disabled || this.state.render) {
return this.props.children;
}
if (this.props.noLoader) {
return false;
}
return this.props.loader;
}
}
export const makeLazy = Comp => {
return props => (
<Lazy>
<Comp {...props}/>
</Lazy>
)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment