I want to show/hide the search bar on the top side of the screen. I am trying to implement an operation where the search bar is shown when the search button is pressed and hides again when the close button of the search bar is pressed.
const showSearchBar = () => {
document.querySelector("#hearder_search_bar").style = {
top : 0
}
};
const hideSearchBar = () => {
document.querySelector("#hearder_search_bar").style = {
top : -71
}
};
return (
<>
<form id = "hearder_search_bar" action="#" className="header__search">
<input type="text" placeholder="Search"/>
<button
type="button"
class="search"
onClick={...}
>
</button>
<button
type="button"
className="close"
onClick={hideSearchBar}
>
</form>
<div className="header__action--search">
<button
className="header__action-btn"
type="button"
onClick={showSearchBar}>
</button>
</div>
</>
);
css
.header__search {
position: absolute;
left: 0;
top: -71px;
}
use react useState hook and let react handle the manipulation of the DOM.
const [shouldShowSearch, setShouldShowSearch] = useState(false);
const toggleShowSearch = () => setShouldShowSearch(prev => !prev);
const label = shouldShowSearch ? 'hide' : 'show';
const top = shouldShowSearch ? '70px' : '0';
//... code
<>
<form id="hearder_search_bar" action="#" className="header__search" style={{top}}>
// ... code
<button
type="button"
className={label}
onClick={toggleShowSearch}
>
</form>
// .. code
<button onclick={toggleShowSearch}>{label} search</button>