Answers for "how to trigger scroll to top in react-native"

2

react native scroll to top function componet

export const Parent : FC<ParentProps> = props => {
    const scrollRef = useRef<ScrollView>();

    const onFabPress = () => {
        scrollRef.current?.scrollTo({
            y : 0,
            animated : true
        });
    }

    return (
        <View>
            <ScrollView ref={scrollRef}>
                {/* Your content here */}
            </ScrollView>
            <FloatingButton onPress={onFabPress} />
        </View>  
    );
}

export const FloatingButton : FC<FloatingButtonProps> = props => {
    const { onPress } = props;

    const onFabPress = () => {
        // Do whatever logic you need to
        // ...

        onPress();
    }

    return (
        <Fab position="bottomRight" onPress={onFabPress}>
            <Icon name="arrow-round-up" />
        </Fab>
    );
}



if you are using flatlist 


    const scrollRef = useRef<Flatlist>();


    const onFabPress = () => {
        scrollRef.current?.scrollToOffset({
            y : 0,
            animated : true
        });
    }

    
    
scrollToOffset is flatlist fucntion
Posted by: Guest on May-21-2021
0

scroll to top react

//__view.jsx
const ScrollTopView = (props) => {
	const { onScroll, onVisbile, visible } = props

	console.log(visible)
	if (typeof window === 'object') window.addEventListener('scroll', onVisbile)

	return (
		<>
			<div
				style={{
					position: 'fixed',
					bottom: 30,
					right: 30
				}}>
				<button
					className='btn btn-primary btn-small'
					onClick={onScroll}
					style={{ display: visible ? 'inline-block' : 'none', borderRadius: 5 }}>
					ScrollTop
				</button>
			</div>
			<h1 style={{ position: 'fixed', bottom: 25, left: '40%', display: visible ? 'inline-block' : 'none' }}>End Scroll</h1>
		</>
	)
}

export default ScrollTopView

// index.jsx
import ScrollTopView from './__view'
import { createElement, useState } from 'react'

const ScrollTop = () => {
	const [visible, setVisible] = useState(false)

	const onVisbile = () => {
		const scrolled = document.documentElement.scrollTop
		if (scrolled >= 600) setVisible(true)
		else if (scrolled <= 300) setVisible(false)
	}

	const onScroll = () => {
		if (typeof window === 'object') window.scrollTo({ top: 0, behavior: 'smooth' })
	}

	return createElement(ScrollTopView, {
		onScroll,
		onVisbile,
		visible
	})
}

export default ScrollTop
Posted by: Guest on June-25-2021

Code answers related to "how to trigger scroll to top in react-native"

Code answers related to "Javascript"

Browse Popular Code Answers by Language