Ad

This.state Null In Reactjs Component

- 1 answer

i am just trying first something simple like only printing the this.state.validForm in the handleSubmit function, but i cant seem to access this.state.validForm. First i tried directly then with this function, but to no avail. I am new to react.

import React, { Component } from 'react';
import TextInput from './TextInput';

class RequestForm extends Component {
    constructor(props) {
        super(props);
        this.state = {validForm : "false"};
        this.getInfoForm = this.getInfoForm.bind(this);
    }

    getInfoForm() {
        return this.state.validForm;
    }

    handleSubmit(event) {
        event.preventDefault();
        console.log('submit values are');
        console.log(event.target.src.value);
        console.log(event.target.email.value);
        console.log(this.state.validForm);
        console.log(this.getInfoForm());
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <TextInput
                    uniqueName="email"
                    name="email"      
                    text="Email Address"
                    required={true}     
                    minCharacters={6}
                    validate="email" 
                    errorMessage="Email is invalid"
                    emptyMessage="Email is required"
                />

                <TextInput 
                    text="User"
                    name="User src"
                    required={true}
                    minCharacters={3}
                    validate="notEmpty"
                    errorMessage="Name is invalid"
                    emptyMessage="Name is required"
                />

                <button type="submit">Submit</button>
            </form>
        );
    }
}

export default RequestForm;
Ad

Answer

The issue is with your render method. Your onSubmit event has its own context so when you do this.handleSubmit, you're going to be passing the wrong context to handleSubmit. Simply bind this and you'll be set!

<form onSubmit={this.handleSubmit.bind(this)}>

Or with the proposed bind operator:

<form onSubmit={::this.handleSubmit}>
Ad
source: stackoverflow.com
Ad