I want to animate a search icon on click in React. I am using useRef hook to get the element and I pass some custom style to the component.
const [searchBar, setSearchBar ] = useState(false);
const searchIcon = useRef();
const searchIconStyle = {
transition: 'rotate .3s ease', // smooth transition
rotate: searchBar? "360deg" : "0",
}
function handleSearchClick(e) {
setSearchBar(prevState => !prevState);
}
So, the code from above is working first time when I click, but it doesn't afterwards. The search icon is a FontAwesome component
{searchBar && <input type="search" placeholder="Search product..."/>}
<FontAwesomeIcon icon={faMagnifyingGlass} className="search-icon"
onClick={handleSearchClick} ref={searchIcon} style={searchIconStyle}/>
How can I animate the icon on each click (depending on the change of searchBar variable?)
CodePudding user response:
I like use classnames. Example for you:
className={classNames(
{ 'basicStyle': true},
{ 'withoutAnimation': !searchBar },
{ 'withAnimation': searchBar },
)}
CodePudding user response:
you're not setting the rotate property properly.
just change :
rotate: searchBar? "360deg" : "0",
to :
rotate: searchBar? "360deg" : "0deg",
this is a demo in codesandbox ( I used a button instead of FontAwesomeIcon cause you didn't tell which library you are using)