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.
TextInputclass 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} />
)
}
}
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.