Reputation:
I have created an InputField
component built from Material UI. When I am trying to pass onKeyPress
to it, it does not work. When I change InputField
to input
, the code works. onKeyPress
is not a prop of InputField
.
Input Component:
<InputField
className={classes.InputContainer}
value={props.whatInput}
onChange={(e) => props.updateInputValue(e, "what")}
placeholder={"Job title, keywords or school"}
type="text"
onKeyPress={handleKeyPress}
/>
handleKeyPress
Function:
const handleKeyPress = (ev) => {
if (ev.key === "Enter") {
router.push({
pathname: "/teaching-jobs",
query: {
search_keywords: props.whatInput ? props.whatInput : "",
search_region: props.whereInput ? props.whereInput : "",
},
});
props.searchWhat();
ev.preventDefault();
}
};
Tech Stack:
Upvotes: 1
Views: 1874
Reputation: 2108
Use the TextField
component:
<TextField
onKeyPress={(e) => {
if (e.key === "Enter") {
e.preventDefault();
handleEnter();
}
}}
/>
BTW - type="text"
is the default for TextField
so it's redundant here.
Upvotes: 0
Reputation: 341
You can use it this way
onKeyPress= {(e) => {
console.log(' key pressed');
handleKeyPress(e)
}}
For more information you can refer to https://reactjs.org/docs/events.html#keyboard-events
Upvotes: -1