Answer the question
In order to leave comments, you need to log in
I need when clicking on the 'search' icon, with limited text input, to give an error like this: 'Sorry! Maximum length 150 characters'.?
const SearchForm = () => {
const [isSearchOpen, setSearchOpen] = useState(false),
formRef = useRef(null);
useClickOutside(formRef, () => setSearchOpen(false));
const [inputText, setInputText] = useState("");
const handleSubmit = e => {
if (inputText.length >= 150 ) {
e.preventDefault();
}
};
return (
<form
ref={formRef}
className={cn("search-form", {
"search-form--focus": isSearchOpen,
})}
onClick={() => setSearchOpen(true)}
onKeyPress={() => setSearchOpen(true)}
action="/search"
// eslint-disable-next-line
role="searchbox"
onSubmit={handleSubmit}
>
<input
value={inputText}
onChange={e => setInputText(e.target.value)}
className="search-form__input"
name="filter"
type="text"
/>
<button
className="search-form__button"
type="submit"
aria-label="Header search button"
/>
</form>
);
};
Answer the question
In order to leave comments, you need to log in
What is the problem?
You have already written the handleSubmit function, now make the block in which you want to display the error message.
When the block is ready, add some state with default value - false
In handleSubmit change this value to true after preventDefault();
If the value is true - draw the block with an error
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question