Search animation

Search bar with different search term animation

import React, {useEffect, useRef, useState} from 'react';
import {Animated} from 'react-native';
import {Box, Flexbox, Icon, Text, Actionable} from '@evlop/native-components';

export default function App({data}: NativeAppBlockProps) {
  const queries: string[] = (data && data.queries) || [
    'smart phones',
    'gaming laptops',
    'water proof watches',
  ];

  const searchbarBackgroundColor = (data && data.searchbarBackgroundColor) || 'primary-50';
  const searchbarTintColor = (data && data.searchbarTintColor) || 'gray-700';

  const progress = useRef(new Animated.Value(1)).current;
  const [activeIndex, setActiveIndex] = useState(0);
  const [displayIndex, setDisplayIndex] = useState(0);

  // cycle queries every 5s
  useEffect(() => {
    const interval = setInterval(() => {
      setActiveIndex(i => (i + 1) % queries.length);
    }, 5000);
    return () => clearInterval(interval);
  }, [queries.length]);

  // animate on activeIndex change
  useEffect(() => {
    Animated.timing(progress, {
      toValue: 0,
      duration: 350,
      useNativeDriver: true,
    }).start(() => {
      setDisplayIndex(activeIndex);
      Animated.timing(progress, {
        toValue: 1,
        duration: 2000,
        useNativeDriver: true,
      }).start();
    });
  }, [activeIndex, progress]);

  const translateX = progress.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 300],
  });

  const AnimatedBox = Animated.createAnimatedComponent(Box as any);

  const animatedStyle: any = {
    width: '100%',
    transform: [{translateX}],
    position: 'absolute',
    zIndex: 100,
    left: 45,
    top: 0,
    bottom: 0,
  };

  return (
    <Actionable action={data?.action}>
      <Box>
        <Box
          px="md"
          py="xs"
          borderRadius={40}
          borderWidth={1}
          borderColor={searchbarTintColor}
          mx="md"
          my="xs"
          position="relative"
          overflow="hidden"
          bg={searchbarBackgroundColor}
        >
          <Flexbox flexDirection="row" alignItems="center">
            <Box mr="3xs">
              <Icon color={searchbarTintColor} icon="feather:search" size={16} />
            </Box>
            <Text color={searchbarTintColor}>{queries[displayIndex]}</Text>
          </Flexbox>

          <AnimatedBox bg={searchbarBackgroundColor} style={animatedStyle} />
        </Box>
      </Box>
    </Actionable>
  );
}
Loading...