Skip to content

Instantly share code, notes, and snippets.

@brunolemos
Last active November 24, 2017 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brunolemos/27875014be454b8c70805044955c09d5 to your computer and use it in GitHub Desktop.
Save brunolemos/27875014be454b8c70805044955c09d5 to your computer and use it in GitHub Desktop.
React Native - ListView receiving data as a prop <ListView data={[1,2,3]} />
import React from 'react';
import { ListView } from 'react-native';
export default class extends React.PureComponent {
constructor(props) {
super(props);
const { data, dataSource, rowHasChanged: _rowHasChanged } = props;
this.state.data = data || [];
const rowHasChanged = _rowHasChanged !== undefined ? _rowHasChanged : this.rowHasChanged;
const ds = dataSource || new ListView.DataSource({ rowHasChanged });
this.state.dataSource = ds.cloneWithRows(this.state.data);
}
state = {
dataSource: null,
};
componentWillReceiveProps({ data }) {
const { data: oldData } = this.props;
if (data !== oldData) {
const dataSource = this.state.dataSource.cloneWithRows(data || []);
this.setState({ dataSource });
}
}
rowHasChanged = (r1, r2) => r1 !== r2;
props: {
data: Array,
dataSource?: ?Object,
rowHasChanged?: Function,
style?: ?Object,
contentContainerStyle?: ?Object,
renderRow: Function,
renderHeader?: Function,
renderFooter?: Function,
};
render() {
const { ...props } = this.props;
delete props.dataSource;
return (
<ListView
dataSource={this.state.dataSource}
enableEmptySections
{...props}
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment