Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "setState is not a function" in React Native when attempting to fire a function from a listener

Tags:

react-native

Im attempting to hide a logo on my app when the keyboard slides up. Unfortunately the Keyboard Avoiding View makes the logo look bad, so I rather just hide the logo entirely.

My current set up is this:

import React, { Component } from 'react';
...
import {
    TextInput,
    Keyboard,
    ...
} from 'react-native';


class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            ...,
            logoShow: true
        };
    }

    _keyboardDidShow () {
        this.setState({
            logoShow: false
        });
    }

    _keyboardDidHide () {
        this.setState({
            logoShow: true
        });
    }

    ...

    componentWillMount(){
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
    }

    componentWillUnmount () {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
    }

    ...

    render() {
        ...
        <View>
            <TextInput style={...}
                       ...
                       onSubmitEditing={Keyboard.dismiss}

            />
        </View>
}

However in this set up, I get a red screen stating that "this.setState is not a function". I THINK this might be because Im attaching the function to the listener as this.setState works correctly in other places in this component, but I am unsure how to bubble up the returned state from the listener to the component's state.

like image 835
JSArrakis Avatar asked Nov 27 '25 23:11

JSArrakis


2 Answers

You need to call this.listener.bind(this) or s => this.listener(s)

It's because JavaScript is passing Keyboard as this and Keyboard doesn't have a _keyboardDidShow method

Related: How does the "this" keyword work?

Also related: Use of the JavaScript 'bind' method

like image 115
woodpav Avatar answered Dec 01 '25 17:12

woodpav


You can define this function as an arrow function. Eg -

_keyboardDidShow = () => { this.setState({ logoShow: false }); }

like image 36
Asiri Piyajanaka Avatar answered Dec 01 '25 18:12

Asiri Piyajanaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!