I have a React component called Collapsible that contains a react-icon named FaArrowDown. How do I make the icon rotate 180 degrees every time a user clicks on it? I have already tried to make it rotate using state but without success. This is the content of the Collapsible.js:
import React, { useState } from "react";
import styled from "styled-components";
import { FaArrowDown } from "react-icons/fa";
import './Collapsible.css'
export const ButtonWrapper = styled.div`
font-size: 25px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding-bottom: 25px;
//transform: rotateX(180deg);
&:hover {
font-size: 30px;
}
`
const Collapsible = (props) => {
const [isOpen, setIsOpen] = useState(false);
return (
<div className="collapsible">
<ButtonWrapper className="toggle" >
<h3 className="my_header" style={{paddingBottom: 25, fontSize: '20px', cursor: "pointer"}} >Best foods</h3>
<FaArrowDown onClick={() => setIsOpen(!isOpen)} style={{cursor: "pointer", transition: "all 0.2s linear"}} />
</ButtonWrapper>
<div className={isOpen ? "content show" : "content"}>{props.children}</div>
</div>
);
};
export default Collapsible;
You could wrap your icon with a styled-component and use css transitions:
// Wrap FaIcon in styled component
const StyledIcon = styled((props) => {
<FaArrowDown {...props} />
})`
cursor: pointer;
transition: transform 0.3s ease-out;
${props => props.active && css`
transform: rotate(180deg);
`}
`;
// And use it like:
<StyledIcon onClick={() => setActive(!isOpen)} active={isOpen} />