I have a form to create users, and the user can paste a delimited list of email addresses into a TextField, where they are turned into Chips.
const MultiUserAdd = () => {
const [emails, setEmails] = useState<string[]>([]);
const handleEmailChange = (newEmails: string[]) => {
setEmails(newEmails);
console.log(emails);
};
const handlePaste = (event: React.ClipboardEvent<HTMLDivElement>) => {
const clipboardData = event.clipboardData?.getData('text/plain');
if (clipboardData) {
const cleanedEmails = clipboardData
.replace(/[\s,]+/g, ' ')
.trim()
.split(' ')
.filter((email) => email.includes('@'));
handleEmailChange([...emails, ...cleanedEmails]);
}
event.preventDefault();
};
const handleDelete = (index: number) => {
const newEmails = [...emails];
newEmails.splice(index, 1);
handleEmailChange(newEmails);
};
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const newEmails = event.target.value.split(',');
handleEmailChange(newEmails);
};
return (
<>
<Box
component="form"
onSubmit={onSubmit}
>
<Typography id="modal-modal-title" variant="h4" component="h4">
Bulk Add Users via Email
</Typography>
<FormControl>
<TextField
variant="outlined"
fullWidth
multiline
placeholder="Enter or paste email addresses"
onPaste={handlePaste}
value={emails.join(',')}
onChange={handleChange}
InputProps={{
startAdornment: emails.map((email, index) => (
<Chip key={index} label={email} onDelete={() => handleDelete(index)} />
)),
inputProps: {
style: {
display: 'flex',
flexWrap: 'wrap'
}
}
}}
/>
</FormControl>
</Box>
</>
);
};
However, once the list is pasted, the chips just continue outside of the TextField. I tried adding the multiline prop, but it does not solve the chip issue. I am thinking that there is something incorrect with my paste function, but I cannot seem to see it.