G
G
Garri_Klim2021-10-27 10:32:06
React
Garri_Klim, 2021-10-27 10:32:06

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>
    );
};


//screenshot of the picture
6178ffae8d700052109298.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Zhivagin, 2021-10-27
@Krasnodar_etc

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 question

Ask a Question

731 491 924 answers to any question