I was trying to make an animated search bar that open upon clicking on the search icon in React. I have added background colors to clearly show what is happening
Here is the codesandbox
The code is but lengthy but let me break it down break down quickly.
I have a flexbox nav-container. It has 2 elements - logo and search icon. Logo initially occupies all the remaining space (because of flex-grow) and search icon occupies only required amount of space.
When search icon is clicked search input expands from 0 to a fixed width and pushes the logo to left.
Also i place the same search icon inside search input by setting the position of search-bar-mobile div to relative and search icon to absolute.
But when search bar is closed position: absolute is immediately removed from search icon making it snap immediately to its original position. But i want to transition smoothly, can you please suggest any fix.
You have to do two thing
First - Change the style of the following class like this
.search-icon-mobile-active {
color: var(--clr-grey-5);
font-size: 10px;
}
Secondly place the input component after the search icon in the code
<form className="search-form-mobile">
<FaSearch
className={`nav-icon search-icon-mobile ${
searchBarMobileActive ? "search-icon-mobile-active" : ""
}`}
onClick={() => setSearchBarMobileActive(true)}
/>
<FaTimesCircle
className={`search-close-button-mobile ${
searchBarMobileActive ? "search-close-button-mobile-active" : ""
}`}
onClick={() => setSearchBarMobileActive(false)}
/>
<input
type="text"
className={`search-input-mobile ${
searchBarMobileActive ? "search-input-mobile-active" : ""
}`}
onBlur={() => setSearchBarMobileActive(false)}
/>
<button
type="submit"
className="search-submit-button-mobile"
></button>
</form>
So the size of the icon will change smoothly and the width animation will depend on the input.