Skip to content

Instantly share code, notes, and snippets.

@padupuy
Created October 18, 2017 07:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save padupuy/7d14ca29761d202fa241a463f8e1d6f8 to your computer and use it in GitHub Desktop.
Save padupuy/7d14ca29761d202fa241a463f8e1d6f8 to your computer and use it in GitHub Desktop.
React Native Swiper
import React, { Component } from 'react';
import { StyleSheet, FlatList, Dimensions, View } from 'react-native';
import styled from 'styled-components/native';
const SCREEN_WIDTH = Dimensions.get('window').width;
const width = SCREEN_WIDTH;
const InactiveDot = styled.View`
background-color: ${props => props.theme.slider.inactive.backgroundColor};
width: 8;
height: 8;
border-radius: 4;
margin-left: 3;
margin-right: 3;
margin-top: 3;
margin-bottom: 3;
`;
const ActiveDot = InactiveDot.extend`
background-color: ${props => props.theme.slider.active.backgroundColor};
`;
/**
* code from @ericvicenti
* source: https://github.com/ericvicenti/react-native-live/blob/master/PhotoViewer.js
*/
export default class Slider extends Component<{}> {
state = this.initState(this.props);
initState(props) {
return {
index: props.index
};
}
onItemChange = item => {
this.setState({
index: item.index
});
this.props.onChange && this.props.onChange(item);
};
renderPagination = () => {
const total = this.props.data.length;
if (total <= 1) {
return null;
}
let dots = [];
for (let key = 0; key < total; key++) {
dots.push(
key === this.state.index ? (
// Active dot
<ActiveDot key={key} />
) : (
// Other dots
<InactiveDot key={key} />
)
);
}
return (
<View pointerEvents="none" style={styles.pagination}>
{dots}
</View>
);
};
keyExtractor = item => item.id;
renderScrollView = () => {
return (
<FlatList
scrollEnabled={true}
ref={fl => {
this.flatList = fl;
}}
keyExtractor={this.keyExtractor}
style={this.props.style}
contentContainerStyle={this.props.itemStyle}
horizontal={true}
pagingEnabled={true}
data={this.props.data}
initialNumToRender={1}
showsHorizontalScrollIndicator={false}
onViewableItemsChanged={({ viewableItems }) => {
const item = viewableItems[0];
if (item && item.key !== this.selectedItemKey) {
this.selectedItemKey = item.key;
this.onItemChange(item);
}
}}
renderItem={({ item }) => {
return <View style={styles.item}>{this.props.renderItem(item)}</View>;
}}
getItemLayout={(data, index) => ({
length: width,
index,
offset: index * width
})}
initialScrollIndex={this.props.index}
/>
);
};
render() {
return (
<View>
{this.renderScrollView()}
{this.renderPagination()}
</View>
);
}
}
const styles = StyleSheet.create({
item: {
width: width,
justifyContent: 'center',
alignItems: 'center'
},
pagination: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'flex-end',
backgroundColor: 'transparent',
marginTop: 10,
marginBottom: 20
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment