Curious_guy
Curious_guy

Reputation: 161

scrollIntoView does not work on react native

I just implemented scrollIntoView to scroll to an element when an event occurs , it works well in web browsers but while testing it in ios simulator it throws this error , is there any replacement for scrollIntoView on react-native or I am doing something wrong ?

error:

TypeError: inputRefs[propertyName].scrollIntoView is not a function. (In 'inputRefs[propertyName].scrollIntoView({
              behavior: 'smooth',
              block: 'center',
              inline: 'start'
            })', 'inputRefs[propertyName].scrollIntoView' is undefined)

Here is what i am using, this works fine on web

inputRefs[propertyName]?.scrollIntoView({
                            behavior: 'smooth',
                            block: 'center',
                            inline: 'start',
                        });

Upvotes: 1

Views: 1271

Answers (1)

Gaurav Roy
Gaurav Roy

Reputation: 12215

scrollIntoView is not supported by native android and ios i guess

rather use scrollTo

here's the expo snack you can check https://snack.expo.dev/@gaurav1995/trusting-orange

import React,{useState,useEffect,useRef} from 'react';
import { Text, View, StyleSheet ,ScrollView } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

export default function App() {

  const data = [1,2,3,4,5,6,7,8,9,10]

  const newRef = useRef()

  useEffect(() => {
    setTimeout(() => {
      newRef.current.scrollTo({y:300,animated:true})
    },2000)
  },[])

  return (
    <View style={styles.container}>
     <ScrollView ref={newRef} >
     {data.map((data) => {
       return(
         <View style={{height:100,backgroundColor:'#611423',marginVertical:10}} >
         <Text>{data}</Text>
         </View>
       )
     })}
     </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Hope it helps. feel free for doubts

Upvotes: 1

Related Questions