Wonderio619
Wonderio619

Reputation: 135

How to properly set onKeyPress event for Material UI text field?

So I have TextField component from Material UI like this:

<TextField
          id="todo-textarea"
          label="Enter new todo"
          placeholder="ToDo"
          onChange={this.props.toDoOnChange}
          onKeyPress={(ev) => {
            if (ev.ctrlKey && ev.key === 'Enter') {
                this.props.addHandler
            }
          }}
          value={this.props.toDoValue}
          className={classes.textField}
          margin="normal"
          helperText="Press Ctrl+Enter to add new ToDo"
        />

and I want to call addHandler method (which add input value in to-do field) when I press ctrl+enter, but this stuff is not working. Currently I call addHandler method by pressing a button, and it works good. Look's like smth wrong with method call from onKeyPress, because I have this message in console: Expected an assignment or function call and instead saw an expression no-unused-expressions

Can you tell me what is wrong here ?

Upvotes: 1

Views: 7149

Answers (1)

md.warish Ansari
md.warish Ansari

Reputation: 137

you should call function like this

   this.props.addHandler() // with the brackets

so now the code looks like

      <TextField
      id="todo-textarea"
      label="Enter new todo"
      placeholder="ToDo"
      onChange={this.props.toDoOnChange}
      onKeyPress={(ev) => {
        if (ev.ctrlKey && ev.key === 'Enter') {
            this.props.addHandler() // here was the mistake
        }
      }}
      value={this.props.toDoValue}
      className={classes.textField}
      margin="normal"
      helperText="Press Ctrl+Enter to add new ToDo"
    />

Upvotes: 2

Related Questions