DEV Community

Noor Said
Noor Said

Posted on

How to change state with isFocused method

I'm using GooglePlacesAutocomplete in my react-native app. Since the component does not provide an onPress method which would normally detect a touch gesture, I would like to use the isFocused method which according to documentation, "returns true if the TextInput is currently focused; false otherwise". My question is what is the convention for watching the return value of a method in react-native? I would like to be able to alter my UI in case the method evaluates to either true/false.

I've provided my setup below. As you can see, as an example, I would like my view to show "Hello" if isFocused evaluates to true and "Hi" if false however this implementation does not obviously won't work for what I'm trying to do

import React, { useEffect, useRef, useState } from 'react'
import { Animated, Pressable, StyleSheet, Text, Touchable, TouchableOpacity, TouchableWithoutFeedback, View } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome';
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete'
import { GOOGLE_PLACES_API_KEY } from '@env'

export default function SearchComponent({ expanded = false, setExpanded }) {

    const ref = useRef();
    const [top] = useState(new Animated.Value(0))

    useEffect(() => {
        Animated.timing(top, {
            toValue: !expanded ? 70 : 80,
            duration: 150,
            useNativeDriver: false
        }).start();
    }, [expanded, top]);

    return (
        < Animated.View style={{ top }
        } >
            <GooglePlacesAutocomplete
                ref={ref}
                placeholder='Search'
                onPress={(data, details = null) => {
                    console.log(data, details);
                }}
                query={{
                    key: GOOGLE_PLACES_API_KEY,
                    language: 'en',
                    components: 'country:ca'
                }}
            />
            {ref.current?.isFocused() ? (
                <Text>Hello</Text>
            ) : (<Text>Hi</Text>)
            }
        </Animated.View>
    )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)