72 lines
2.1 KiB
TypeScript
72 lines
2.1 KiB
TypeScript
|
import React, { useState } from "react";
|
||
|
|
||
|
const MultiEmailInvite: React.FC = () => {
|
||
|
const [emails, setEmails] = useState<string[]>([]);
|
||
|
const [inputValue, setInputValue] = useState("");
|
||
|
|
||
|
const handleAddEmail = () => {
|
||
|
const trimmedEmail = inputValue.trim();
|
||
|
|
||
|
// Validate email
|
||
|
if (!trimmedEmail || !validateEmail(trimmedEmail)) {
|
||
|
alert("Please enter a valid email address.");
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// Check for duplicates
|
||
|
if (emails.includes(trimmedEmail)) {
|
||
|
alert("This email has already been added.");
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// Add email to the list
|
||
|
setEmails([...emails, trimmedEmail]);
|
||
|
setInputValue(""); // Clear the input field after adding
|
||
|
};
|
||
|
|
||
|
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||
|
if (e.key === "Enter" || e.key === ",") {
|
||
|
e.preventDefault();
|
||
|
handleAddEmail();
|
||
|
}
|
||
|
};
|
||
|
|
||
|
const handleRemoveEmail = (emailToRemove: string) => {
|
||
|
setEmails(emails.filter((email) => email !== emailToRemove));
|
||
|
};
|
||
|
|
||
|
const validateEmail = (email: string) => {
|
||
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||
|
return emailRegex.test(email);
|
||
|
};
|
||
|
|
||
|
const [inputFocus, setInputFocus] = useState(false);
|
||
|
|
||
|
return (
|
||
|
<div className="multi-email-invite-input-container">
|
||
|
<div className={`multi-email-invite-input${inputFocus ? " active" : ""}`}>
|
||
|
{emails.map((email, index) => (
|
||
|
<div key={index} className="entered-emails">
|
||
|
{email}
|
||
|
<span onClick={() => handleRemoveEmail(email)}>×</span>
|
||
|
</div>
|
||
|
))}
|
||
|
<input
|
||
|
type="text"
|
||
|
value={inputValue}
|
||
|
onChange={(e) => setInputValue(e.target.value)}
|
||
|
onFocus={() => setInputFocus(true)}
|
||
|
onBlur={() => setInputFocus(false)}
|
||
|
onKeyDown={handleKeyDown}
|
||
|
placeholder="Enter email and press Enter or comma"
|
||
|
/>
|
||
|
</div>
|
||
|
<div onClick={handleAddEmail} className="invite-button">
|
||
|
Invite
|
||
|
</div>
|
||
|
</div>
|
||
|
);
|
||
|
};
|
||
|
|
||
|
export default MultiEmailInvite;
|