1

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:

  1. "next": "^9.5.1",
  2. "react": "^17.0.2",
  3. "@material-ui/core": "^4.11.0",
  4. "@material-ui/icons": "^4.9.1",
  5. "@material-ui/lab": "^4.0.0-alpha.56",
  6. "@material-ui/pickers": "^3.2.10",
  7. "@mui/icons-material": "^5.3.1",
  8. "@mui/material": "^5.3.1",
  9. "@mui/x-data-grid": "^5.5.0",
  • refer to this thread https://stackoverflow.com/questions/45993523/how-can-i-add-onkeypress-event-to-react-material-ui-textfield this might help you out. – Sakshi Mahajan Feb 22 '22 at 07:45
  • @SakshiMahajan, thank you for taking the time to share this. Unfortunately, `onKeyDown`, `onKeyUp` and `onKeyPress` do not work. I wonder whether Material UI support these. –  Feb 22 '22 at 08:17

2 Answers2

0

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.

I.sh.
  • 252
  • 3
  • 13
-1

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

Shambhu Sahu
  • 342
  • 2
  • 4
  • Thank you for taking the time to answer this question. Unfortunately your suggestion did not work. –  Feb 22 '22 at 07:24