Hi. I’m using react-hook-form and react-tag-input. I’m trying to prevent form submission…
- User
Hi. I’m using react-hook-form and react-tag-input. I’m trying to prevent form submission on hitting ‘enter’ button. This is my code, I’m trying to use e.preventDefault() but it’s not working… could you help? import * as React from ‘react’; import * as i from ‘types’;
import { TagsInput } from ‘react-tag-input-component’; import { FormField } from ‘common/form’; import { Container } from ‘./styled’;
const formatValue = (value: string[] | string | undefined) => { if (Array.isArray(value)) { return value; }
if (value) { return value.split(', '); }
return []; };
export const TagInput: React.FC = ({ value, onChange, placeholder, name, label, description, error, }) => { const formFieldProps = { name, label, error, description };
const handleBlur = (e: React.ChangeEvent) => { const inputValue = e.target.value; if (inputValue) { onChange([…formatValue(value), inputValue]); e.target.value = ‘’; } };
const handleClick = (e: React.SyntheticEvent) => { const { tagName } = e.target as HTMLDivElement | HTMLInputElement;
if (tagName === ‘DIV’) { const input = (e.target as Node).lastChild as HTMLInputElement; input.focus(); }
if (tagName === ‘INPUT’) { (e.target as HTMLInputElement).focus(); } };
const handleKeyUp = (e: React.KeyboardEvent) => { if (e.key === ‘Enter’) { console.log(e); e.preventDefault(); } };
return ( <FormField {…formFieldProps}> <Container isError={!!error} onClick={handleClick} onKeyDown={handleKeyUp}
); };
type TagInputProps = i.FormFieldProps & { onChange: (value: string[]) => void; value: string[]; placeholder?: string; isError?: boolean; };
- Assistant
One possible solution could be to add a state variable that keeps track of whether the enter key was pressed, and conditionally preventDefault() in the onSubmit event handler based on that variable. Here's an example implementation:
const TagInput: React.FC<TagInputProps> = ({ value, onChange, placeholder, name, label, description, error, }) => { const [enterKeyPressed, setEnterKeyPressed] = React.useState(false); const formRef = React.useRef<HTMLFormElement>(null); const formatValue = (value: string[] | string | undefined) => { if (Array.isArray(value)) { return value; } if (value) { return value.split(", "); } return []; }; const handleBlur = (e: React.ChangeEvent<HTMLInputElement>) => { const inputValue = e.target.value; if (inputValue) { onChange([...formatValue(value), inputValue]); e.target.value = ""; } }; const handleClick = (e: React.SyntheticEvent) => { const { tagName } = e.target as HTMLDivElement | HTMLInputElement; if (tagName === "DIV") { const input = (e.target as Node).lastChild as HTMLInputElement; input.focus(); } if (tagName === "INPUT") { (e.target as HTMLInputElement).focus(); } }; const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === "Enter") { setEnterKeyPressed(true); } }; const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); if (!enterKeyPressed) { formRef.current?.submit(); } setEnterKeyPressed(false); }; return ( <FormField name={name} label={label} error={error} description={description}> <Container isError={!!error} onClick={handleClick}> <form ref={formRef} onSubmit={handleSubmit}> <TagsInput value={formatValue(value)} onChange={onChange} name={name} onBlur={handleBlur} placeHolder={placeholder} onKeyUp={handleKeyUp} /> </form> </Container> </FormField> ); };In this implementation, we added a new state variable
enterKeyPressedthat is initially set tofalse. In thehandleKeyUpfunction, we set this variable totrueif the enter key was pressed. In thehandleSubmitfunction, we first prevent default form submission usinge.preventDefault(), and then check ifenterKeyPressedisfalse. If it is, we manually submit the form usingformRef.current?.submit()and resetenterKeyPressedtofalse. Otherwise, we do nothing and the form submission is prevented.We also wrapped the
TagsInputcomponent in a separate<form>element, which allows us to handle theonSubmitevent separately from the parent component'sonKeyDownevent. - User
I do not need to submit anything at all. and please do not use refs
- Assistant
In that case, you can simply remove the
<form>element, and handle theonKeyUpevent on theTagsInputcomponent itself. Here's an updated implementation:const TagInput: React.FC<TagInputProps> = ({ value, onChange, placeholder, name, label, description, error, }) => { const [enterKeyPressed, setEnterKeyPressed] = React.useState(false); const formatValue = (value: string[] | string | undefined) => { if (Array.isArray(value)) { return value; } if (value) { return value.split(", "); } return []; }; const handleBlur = (e: React.ChangeEvent<HTMLInputElement>) => { const inputValue = e.target.value; if (inputValue) { onChange([...formatValue(value), inputValue]); e.target.value = ""; } }; const handleClick = (e: React.SyntheticEvent) => { const { tagName } = e.target as HTMLDivElement | HTMLInputElement; if (tagName === "DIV") { const input = (e.target as Node).lastChild as HTMLInputElement; input.focus(); } if (tagName === "INPUT") { (e.target as HTMLInputElement).focus(); } }; const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === "Enter") { setEnterKeyPressed(true); } }; return ( <FormField name={name} label={label} error={error} description={description}> <Container isError={!!error} onClick={handleClick}> <TagsInput value={formatValue(value)} onChange={onChange} name={name} onBlur={handleBlur} placeHolder={placeholder} onKeyUp={(e) => { handleKeyUp(e); e.preventDefault(); }} /> </Container> </FormField> ); };In this implementation, we removed the
<form>element and added theonKeyUpevent handler directly to theTagsInputcomponent. We call both thehandleKeyUpfunction ande.preventDefault()in theonKeyUpevent handler, which prevents the default behavior of submitting the form on Enter key press. - User
does not help
- Assistant
I apologize for the confusion. Here's an updated implementation that should prevent the form submission on hitting the Enter key:
const TagInput: React.FC<TagInputProps> = ({ value, onChange, placeholder, name, label, description, error, }) => { const formatValue = (value: string[] | string | undefined) => { if (Array.isArray(value)) { return value; } if (value) { return value.split(", "); } return []; }; const handleBlur = (e: React.ChangeEvent<HTMLInputElement>) => { const inputValue = e.target.value; if (inputValue) { onChange([...formatValue(value), inputValue]); e.target.value = ""; } }; const handleClick = (e: React.SyntheticEvent) => { const { tagName } = e.target as HTMLDivElement | HTMLInputElement; if (tagName === "DIV") { const input = (e.target as Node).lastChild as HTMLInputElement; input.focus(); } if (tagName === "INPUT") { (e.target as HTMLInputElement).focus(); } }; const handleKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === "Enter") { e.preventDefault(); } }; return ( <FormField name={name} label={label} error={error} description={description}> <Container isError={!!error} onClick={handleClick}> <TagsInput value={formatValue(value)} onChange={onChange} name={name} onBlur={handleBlur} placeHolder={placeholder} onKeyUp={handleKeyUp} /> </Container> </FormField> ); };In this implementation, we added an
onKeyUpevent handler to theTagsInputcomponent that callse.preventDefault()if the Enter key was pressed. This should prevent the form from being submitted on hitting the Enter key.