Search code examples
animationreactjsreact-nativetextinput

react native navbar animation input text


I want to show a cancel (iptal) button, on the focus TextInput animation?

I did the following code, but it hasn't worked:

constructor(props) {
    super(props);
    this.state = { cancelBtn:this.cancelBtn()};
}

cancelBtn(){
    return (<TouchableHighlight style={styles.searchTouch} onPress={this.press()}>
    <Text style={styles.searchBarText}>İptal</Text>
    </TouchableHighlight>);
}

render(){
    <View style={styles.searchBar}>
        <View style={styles.searchBarBox}>
            <TextInput
                ref="searchBarInput"
                style = {styles.searchBarInput}
                placeholder = 'Mekan Ara...'
            />
        </View>
    {this.state.cancelBtn}
    </View>
}

How do I do this in an animated way?

img: s.s.1 => https://i.sstatic.net/m7wxm.png

s.s.2 => https://i.sstatic.net/hYa3z.png


Solution

  • Use the onFocus method of TextInput to trigger an animation. Reverse it with onBlur. Then, display the input based on whether the input is selected (state).

    This example isn't tested from the styling perspective, but should give you an idea. Make sure to read up on the Animation docs too.

    constructor() {
      this.state = {
        inputLength: new Animated.Value(100), // initial value 
        isFocused: false
      }
    }
    
    onFocus() {
      Animated.timing(this.state.inputLenght, {
        toValue: 90, // or whatever value
        duration: 1000
      }).start(() => this.setState({isFocused: true}))
    }
    
    onBlur() {
      Animated.timing(this.state.inputLenght, {
        toValue: 100, // or whatever value
        duration: 1000
      }).start(() => this.setState({isFocused: false}))
    }
    
    
    
    <Animated.View style={{width: this.state.inputLength}}>
      <TextInput
        ref="input"
        onFocus={this.onFocus}
        onBlur={this.onBlur}
        ...
      />
    </Animated.View>
    {this.state.isFocused && (
      <TouchableOpacity onPress={() => this.refs.input.blur()}><Text>Submit</Text></TouchableOpacity>
    )}