-2

I would like to know how to fix the following error:

onChange={this.handleName}

I am aware that I should make the binding inside the constructor and also I cannot make the binding inside the onChange, any ideas?

class Register extends React.Component {
  constructor(props: Props) {
    super(props)
    this.state = {
      name: '',
      surname: '',
      email: '',
    }
  }
  handleName(e) {
    this.setState({ name: e.target.value })
  }
  render() {
    return (
      <Dialog className={classes.root} open={isOpen}>
      <TextField label="NAME" onChange={this.handleName} fullWidth />
      </Dialog>
    )
  }
}
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    This is arguably the most duplicated question for [tag:reactjs] on SO. With 28k rep you should know by now how to first check for existing questions before posting new ones. – Chris Oct 27 '17 at 13:40
  • 1
    @Chris sorry guys but today I was coding with fever :( – GibboK Oct 27 '17 at 18:24

5 Answers5

1

Since your function handleName is not bound to the class, currently the scope of this inside handleName is the function itself and not the class. So there is no setState function in that scope.

To correct this error, you can either put the binding of the function in your constructor.

constructor(props: Props) {
    super(props)
    this.state = {
      name: '',
      surname: '',
      email: '',
    }

    this.handleName = this.handleName.bind(this,e);
  }

Or you can use arrow syntax to define the function

handleName = (e)=> {
...
}
palsrealm
  • 5,083
  • 1
  • 20
  • 25
0

You need to bind handleName to this.

Instead of:

onChange={this.handleName}

Write it like:

onChange={this.handleName.bind(this)}.

This is because you're passing a function reference to onChange so when it executes it will be outside of your current scope, because of that setState won't exist.

anteAdamovic
  • 1,462
  • 12
  • 23
0

Please add bind line in your constructor function.

constructor(props: Props) { .... this.handleName = this.handleName .bind(this); }

0

Make handleName in form of the arrow function, whereby this will be referred to the component instance.

handleName = (e) => { this.setState({ name: e.target.value }); }

Viktor Soroka
  • 187
  • 2
  • 4
0

You should bind your handleName function in the constructor method.

constructor(props: Props) {
    super(props)
    this.state = {
      name: '',
      surname: '',
      email: '',
    }
    this.handleName = this.handleName.bind(this);
}
Mateo Guzmán
  • 1,206
  • 1
  • 15
  • 27