Skip to content

Instantly share code, notes, and snippets.

@slorber

slorber/Lazy.js

Created Apr 23, 2018
Embed
What would you like to do?
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