-1

I am working on some project but I really stuck on this problem. Why I get this error like TypeError: Cannot read property 'text' of undefined, when my program update state onChange but when I clicked on submit button I get this mess, Please help me out.

my code snippet:

import React, { Component } from "react";
import { Form, Button, Input, Label } from "semantic-ui-react";

class FormField extends Component {
  constructor() {
    super();
    this.state = {};
  }

  handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  handleSubmit(event) {
    event.preventDefault();
    const { text } = this.state;
    console.log(text);
  }

  textToCode() {}

  render() {
    return (
      <Form onSubmit={this.handleSubmit}>
        <Form.Field>
          <Label>Enter Text</Label>
          <Input
            name="text"
            value={this.state.text}
            onChange={this.handleChange}
          />
        </Form.Field>

        <Form.Field>
          <Button
            type="submit"
          >
            Submit
          </Button>
        </Form.Field>

        <Form.Field>
          <input disabled />
        </Form.Field>
      </Form>
    );
  }
}

export default FormField;

RinMori
  • 61
  • 1
  • 9
  • Duplicate of http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback but I confused myself and un-hammered it. Doh! – T.J. Crowder Jan 28 '20 at 18:02
  • 1
    There's a big difference between `handleChange` and `handleSubmit`. The first is an arrow function that closes over the correct value of `this`. The other is a *method* that has `this` determined by how it's called, and when it gets called that `this` isn't the correct value. See the answers to the question above for what do do. (I would use `.bind` in the constructor -- both for `handleSubmit` and `handleChange`, making `handleChange` a method.) – T.J. Crowder Jan 28 '20 at 18:03

1 Answers1

0

handlesubmit isn't being passed properly to the event handler. You can write () => this.handlesubmit() in stead.

mzedeler
  • 4,177
  • 4
  • 28
  • 41
  • 1
    This is an ***often*** repeated duplicate. It doesn't need an answer, it's already repeatedly answered ([here](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) amongst other places). – T.J. Crowder Jan 28 '20 at 18:04