Search code examples
reactjsreact-nativereact-native-firebasereact-native-elements

React Native Firebase state undefined


I've tried multiple implementations, and I can't seem to get the state to not be undefined. I've tried arrow functions, I've tried binding this inside the onChange event, and nothing seems to work. Can somebody take my codebase and give me some insight as to what I'm doing wrong? Thanks!

import React from 'react';
import {View, Image, StyleSheet} from 'react-native';
import {Button, Text, Input} from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';

const styles = StyleSheet.create({
    heading: {
        padding: 20,
    },
});

export default class ContactForm extends React.Component
{
    constructor(props) 
    {
        super(props);

        this.state = {
            name: '',
            email: '',
        }
    }

    handleName(e)
    {
        this.setState({name: e.target.value})
        console.log(e.target.value);
    }

    handleEmail(e)
    {
        
    }

    submit(e)
    {
        console.log(this.state.name + " " + this.state.email);
    }

    render() 
    {
    return (
    <View style={styles.heading}>
        <Text h5>Sign up to receive updates/newsletters!</Text>
        <Input placeholder="your name" onChange={this.handleName.bind(this)} />
        <Input placeholder="your email" onChange={this.handleEmail.bind(this)} />
        <Button title="Submit" onPress={this.submit}/>
    </View>
    )
    }
}

Solution

  • Hi you can do it like this there is no need to bind the arrow function with "this".

    export default class ContactForm extends React.Component
    {
        constructor(props) 
        {
            super(props);
    
            this.state = {
                name: '',
                email: '',
            }
        }
    
        handleName=(e)=>
        {   console.log(e);
            this.setState({name: e})
            
        }
    
        handleEmail=(e)=>
        {
            this.setState({email: e})
        }
    
        submit=()=>
        {
            console.log(this.state.name + " " + this.state.email);
        }
    
        render() 
        {
        return (
        <View style={styles.heading}>
            <Text h5>Sign up to receive updates/newsletters!</Text>
            <Input placeholder="your name" onChangeText ={this.handleName} /> 
            //change onChange to onChangeText 
            <Input placeholder="your email" onChangeText={this.handleEmail} />
            <Button title="Submit" onPress={this.submit}/>
        </View>
        )
        }
    }