Integrate text input: "Press enter" keyboard event

Code
Code Component
Code Overrides
Framer
Updated: 2018-10-20

Overview

This is the same idea as the "onChange" example.

The text input here is a standard HTML <input> which supports keypress event. We can wrap this in a code component and expose onAccept as a prop. In the code override, we can hook into onAccept in the same way as onTap, and use the updated text accordingly.

Note: Also check out this post for general tips on working with input in React.

TextInput

class TextInput extends React.Component {
  ...
  handleKeyPress = e => {
    // We pass the new value of the text when calling onAccept
    if (e.key === "Enter") {
      const { onAccept } = this.props;
      onAccept && onAccept(e.target.value);
    }
  }
  render() {
    return (
      // Note we need to use "onKeyPress" instead of "onkeypress"
      // as in HTML.
      <input type="text" onKeyPress={this.handleKeyPress} />
    )
  }
}

Notes

  • "Enter" is just one of the keys that we can handle in onKeyPress, find a list of other keys here.
  • onKeyPress is just one of the supported keyboard events. We can also use onKeyDown or onKeyUp depending on the use case.

Source Code

Check out the complete source code here