Next.js Discord

Discord Forum

Why is this component causing infinite re-renders?

Answered
chan posted this in #help-forum
Open in Discord
I'm trying to make a search bar that does an animation when you click on it. I am clueless as to what is causing the re-renders to loop. Any help would be appreciated!
function SearchBar({ setSearchValue }) {

    const [isSearchVisible, setSearchVisible] = useState(false);

    function handleSearchClick() {
        setSearchVisible(true);
    }

    function handleClearText() {
        setSearchValue('');
    }

    function handleGoBack() {
        handleClearText();
        setSearchVisible(false);
    }

    return (
        <div className="searchbarcontainer">
            <button className='dummysearchbar' onClick={handleSearchClick()} style={{visibility: !isSearchVisible ? "visible" : 'hidden'}}>
                Search
            </button>
            <form className='searchbar' onSubmit={e => { e.preventDefault(); } } style={{visibility: isSearchVisible ? "visible" : 'hidden'}}>
                <input type="text" onChange={(e) => setSearchValue(e.target.value) } />
                <button className='clear-text-button' onClick={handleClearText}></button>
                <button className='go-back-button' onClick={handleGoBack}></button>
            </form>
        </div>
    )
}
Answered by Giant panda
You are calling the handler instead of passing it at onClick={handleSearchClick()}.
View full answer

2 Replies

Giant panda
You are calling the handler instead of passing it at onClick={handleSearchClick()}.
Answer
rookie mistake... thank you!!