2

Could you please look into what i'm missing with scrollview configuration. I'm trying to create a scrollview animation with starting card-child offset by half of device-width, then when the user scrolls, it should align center and as should other rest of the scrollview-children

Basically all children when scrolled should align in center. Also first child should start at the end of the device width.

progress so far -> https://snack.expo.io/@sefeniyuk/scrollview-alignment

thank you.

import * as React from 'react';
import { Text, View, StyleSheet, ScrollView, Dimensions, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';

const { width } = Dimensions.get('window');
const cardPaddingHorizontal = 2;
const cardWidth = width - cardPaddingHorizontal * 2;
const cardleftOffset = width - cardWidth / 3.5;
const initialCardShown = width - cardleftOffset;

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <ScrollView         
          horizontal
          showsHorizontalScrollIndicator={false}
          scrollEventThrottle={1}
          style={styles.style}
          contentContainerStyle={styles.contentContainerStyle}
          snapToAlignment="center"
          decelerationRate="fast"
        >
          {[1, 2, 3, 4].map((num, i) => {
            return (
              <TouchableOpacity key={i} style={styles.card}>
                <View style={styles.content}>
                <Text style={styles.text}>{num}</Text>
                </View>
              </TouchableOpacity>
            );
          })}

        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
    contentContainerStyle: {
    width: cardWidth * 4
  },
  style: {
    paddingLeft: cardleftOffset
  },
  card: {
    backgroundColor: 'red',
    width: cardWidth,
    height: cardWidth,
    margin: cardPaddingHorizontal,
    elavation: 10
  },
  content: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  text: {
    fontSize: 40,
    color: 'white'
  }
});

1 Answers1

2

You can use react state hooks in functional components. You can either a give width for the starting scroll position or the best way is to use

scrollViewRef.current.scrollToIndex({ index: "index-of-item" })

import React, {useRef} from 'react'
    
const App = () => {

   const scrollViewRef = useRef();

   return (
      <ScrollView horizontal={true} ref={scrollViewRef} 
       onContentSizeChange= 
       {() => scrollViewRef.current.scrollTo({x: giveWidth, y: 
       giveHeight, animated: true})}>
       .
       .
       .
       .
      </ScrollView>
   );
}
nadinCodeHat
  • 83
  • 1
  • 7