react-native-carousel-control icon indicating copy to clipboard operation
react-native-carousel-control copied to clipboard

changing parent component state within onPageChange prop results in undesired behavior

Open kaloncheung124 opened this issue 8 years ago • 1 comments

In my app, we have a screen component that contains the carousel and a list of data. We wish to use the carousel onPageHandler to select between different sources for the data. However, when we try to change the screen component state within onPageChange, the carousel pauses and then scrolls back to the first element.

Here is the stripped down code for our home screen with the carousel within it:

export default class HomeScreen extends React.component {

    constructor(props) {
        super(props);
        this.state = {currPageNum: 0};
    }

    ...

    render() {
        return (
            <View>
                <Carousel
                    initialPage={0}
                    pageStyle={{
                        flex: 1,
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'flex-start',
                        padding: 5,
                        backgroundColor: '#f7f7f7',
                    }}
                    sneak={0}
                    swipeThreshold={0.25}
                    onPageChange={(page) => {
                        console.log(page);
                        this.setState({currPageNum: page})
                     }}
                >
                    {...}
                </Carousel>
            </View>
        );
    }

Any help would be greatly appreciated!

kaloncheung124 avatar Jul 26 '17 18:07 kaloncheung124

I think it's due to the currentPage default prop. If I haven't set the currentPage prop, whenever componentWillReceiveProps gets called, it still receives a currentPage prop with a value of 0. This sets this.state.currentPage to 0 whenever the carousel is re-rendered. Perhaps remove this from the default props and add some checking for undefined?

kaloncheung124 avatar Jul 26 '17 22:07 kaloncheung124