user15401250
user15401250

Reputation:

How can I add onKeyPress to a custom React Component?

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",

Upvotes: 1

Views: 1874

Answers (2)

I.sh.
I.sh.

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

Shambhu Sahu
Shambhu Sahu

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

Related Questions