I've tried so much properties from react native docs, did some searches on google and especially stackOverflow but none of them seems to be working on both platforms android and ios simultaneously I don't know which one to use in this case. I have a list of buttons 20 in a ScrollView I want the view to be initially on the button that is in the center.
const buttons = [...Array(21).keys()]
<ScrollView
horizontal
showsHorizontalScrollIndicator={false}
>
{buttons.map(button=> <TouchableOpacity key={button}>button</TouchableOpacity>)}
</ScrollView>
I want the button number 10 to be in the center of the screen as initial view help is appreciated.
In my opinion the better and minimal solution for that is:
// simple array that has numbers from 0 till 20
const buttons = [...Array(21).keys()];
const [scrollView, setScrollView] = useState(null);
const scrollToIndex = (contentSize) => {
// getting desired index of button or you can simply do e.g. (const index = 2)
// for this example you can pass index = 10 or 9 to be centered perfectly or contentSize / 2
const index = options.reduce((acc, option, idx) => (option === 'desired-button-to-be-shown' ? (acc = idx) : acc));
// setting view to be centered on that index
scrollView.scrollTo({ x: (contentSize / options.length) * (index - 1) });
};
// this is your ScrollView Carousel / Slider
<ScrollView
// saving SrcollView reference in state
ref={(scrollViewRef) => setScrollView(scrollViewRef)}
horizontal
// getting the width of the whole ScrollView (all your content e.g. images / buttons)
onContentSizeChange={(contentSize) => scrollToIndex(contentSize)}
showsHorizontalScrollIndicator={false}>
{buttons.map((button) => (
<TouchableOpacity key={button}>button</TouchableOpacity>
))}
</ScrollView>;