2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[React Native] react-native-snap-carouselのPaginationの初期表示を正確にする

Last updated at Posted at 2021-03-10

0. 目的

react-native-snap-carouselのPaginationの初期表示を正確にする

1. 環境

  • React : 16.8.6
  • React Native : 0.63.4

2. ソースコード

ViewSnapCarousel.js
import React from 'react';
import {useState} from 'react';
import {SafeAreaView, View, Text} from 'react-native';

import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from 'react-native-responsive-screen';

import Carousel, {Pagination} from 'react-native-snap-carousel';

function App() {
  const data = [0, 1, 2, 3, 4, 5, 6, 7];
  const [activeDotIndex, setActiveDotIndex] = useState(data.length - 1);

  const viewContents = (items, index) => {
    return (
      <>
        <View
          style={{
            alignItems: 'center',
            justifyContent: 'center',
            height: '100%',
          }}>
          <Text style={{color: 'blue', fontSize: hp('10%')}}>{items.item}</Text>
        </View>
      </>
    );
  };

  return (
    <>
      <SafeAreaView>
        <Carousel
          contentContainerCustomStyle={{
            backgroundColor: 'cyan',
            height: hp('50%'),
          }}
          data={data}
          firstItem={data.length - 1}
          renderItem={(items, index) => viewContents(items, index)}
          onBeforeSnapToItem={(slideIndex) => setActiveDotIndex(slideIndex)}
          itemWidth={wp('100%')}
          sliderWidth={wp('100%')}
          useScrollView
        />
        <Pagination
          containerStyle={{backgroundColor: 'gray', height: hp('50%')}}
          dotsLength={data.length}
          activeDotIndex={activeDotIndex}
        />
      </SafeAreaView>
    </>
  );
}

export default App;

3. 結果

10 10
useScrollViewなし(初期表示 : 5) useScrollViewあり(初期表示 : 7)

Paginationを使用する場合、CarouselのpropsにuseScrollViewを指定することでfirstItemに指定したコンテンツを正しく表示することができる

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?