To create an automatic horizontal scrolling effect for text in React Native, you can leverage the Animated API to smoothly move the text within a designated container. Follow these steps to achieve this effect:
1. Begin by importing the necessary components and initializing the animation.
import React, { useRef, useEffect } from 'react'; import { Animated, Text, View, StyleSheet, Easing } from 'react-native'; const AutomaticHorizontalScroll = ({ text, duration }) => { const scrollX = useRef(new Animated.Value(0)).current; // Measure the width of the text const textWidth = useRef(0); const measureText = event => { textWidth.current = event.nativeEvent.layout.width; };
2. Configure the animation loop that moves the text horizontally.
useEffect(() => { const animation = Animated.loop( Animated.timing(scrollX, { toValue: -textWidth.current, duration: duration || 5000, // Default duration is 5 seconds easing: Easing.linear, useNativeDriver: true, }) ); animation.start(); return () => { animation.stop(); }; }, [scrollX, duration]);
3. Render the text within the animated container, applying the translation based on the animation.
return ( <View style={styles.container}> <Animated.View style={[ styles.textContainer, { transform: [{ translateX: scrollX }] }, ]} > <Text onLayout={measureText} style={styles.text}> {text} </Text> </Animated.View> </View> ); }; const styles = StyleSheet.create({ container: { overflow: 'hidden', }, textContainer: { flexDirection: 'row', alignItems: 'center', }, text: { fontSize: 18, }, }); export default AutomaticHorizontalScroll;
4. Integrate the AutomaticHorizontalScroll component into your app’s structure.
import React from 'react'; import { View, StyleSheet } from 'react-native'; import AutomaticHorizontalScroll from './AutomaticHorizontalScroll'; // Adjust the path const App = () => { return ( <View style={styles.container}> <AutomaticHorizontalScroll text="This is a scrolling text." /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); export default App;