Skip to main content
Version: 1.0.16

onKeyDown

The onKeyDown prop is designed to handle events when a user presses a keyboard key down within the component. This callback is triggered for every keypress event, and it receives a KeyboardEvent object, providing detailed information about the specific key that triggered the event.

Within the ReactMultiEmail component, an internal logic, handleKeyDown, is incorporated, defining actions for specified keys. In addition to this, users have the capability to either further define actions for keys specified in the internal logic or newly define actions for different keys.

info

onKeyDown is triggered when a key is pressed down, executing before the onKeyUp function.

About onKeyDown

  • Property: onKeyDown
  • Type: (evt: React.KeyboardEvent) => void;
  • Default: undefined

Demo

react-multi-email

Input your Email Address

react-multi-email value

empty

currentKey(keyDown):

Code

Full code

OnKeyDown.tsx
import * as React from 'react';
import { ReactMultiEmail } from 'react-multi-email';
import 'react-multi-email/dist/style.css';

export default function multiEmail() {
const [emails, setEmails] = React.useState<string[]>([]);
const [currentKeyDown, setCurrentKeyDown] = React.useState<string>("");

const onKeyDownFunc = (event: React.KeyboardEvent<HTMLInputElement>) => {
console.log(event.key);
setCurrentKeyDown(event.key);
};

return (
<div style={styles}>
<h3>react-multi-email</h3>
<ReactMultiEmail
// onKetDown prop
onKeyDown={onKeyDownFunc}
placeholder="Input your Email Address"
emails={emails}
onChange={(_emails: string[]) => {
setEmails(_emails);
}}
getLabel={(
email: string,
index: number,
removeEmail: (index: number) => void
) => {
return (
<div data-tag key={index}>
{email}
<span data-tag-handle onClick={() => removeEmail(index)}>
×
</span>
</div>
);
}}
/>
<h4>react-multi-email value</h4>
<p>{emails.join(", ") || "empty"}</p>
<div>currentKey(keyDown): {currentKeyDown}</div>
</div>
);
}

const styles = {
fontFamily: "sans-serif",
width: "500px",
border: "1px solid rgb(238, 238, 238)",
background: "rgb(243, 243, 243)",
padding: "25px",
margin: "20px",
color: "black",
};

Code snippet

OnKeyDown.tsx
const onKeyDownFunc = (event: React.KeyboardEvent<HTMLInputElement>) => {
// do something
};

<ReactMultiEmail
onKeyDown={onKeyDownFunc}
/>

Internal logic code (handleOnKeyDown)

ReactMultiEmail.tsx
const handleOnKeydown = React.useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
onKeyDown?.(e);

switch (e.key) {
case 'Enter':
e.preventDefault();
break;
case 'Backspace':
if (!e.currentTarget.value) {
removeEmail(emails.length - 1, false);
}
break;
default:
}
},
[emails.length, onKeyDown, removeEmail],
);