Home > Blockchain >  How can I add onKeyPress to a custom React Component?
How can I add onKeyPress to a custom React Component?

Time:02-22

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

CodePudding user response:

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

CodePudding user response:

The solution is 2 fold.

1. onKeyPress is not passed as a prop to the custom component.

New Props:

const InputField = ({
{...}
  onKeyPress,
}) => {

Return Statement for the custom component:

return (
    <TextField
     {...}
      onKeyPress={onKeyPress}
    >
    </TextField>

2. One must pass the ev parameter as an argument to the handleKeyPress function: <InputField {...} onKeyPress={(ev) => handleKeyPress(ev)} />

  • Related