Search code examples
reactjsjsxcss-transitionsreact-component

How to rotate an element 180 in react?


How can I rotate a <CaretUpFill/> icon to be upside down based a state variable show, but in a transition? I'm in a _rafce. (react arrow function component)

Currently, I am rendering another icon <CaretDownFill/>, but it doesn't look smooth. enter image description here

I want to make the arrow look like this:

enter image description here


        <div className="col-2 d-flex align-items-center">
          <small>{show ? <CaretUpFill /> : <CaretDownFill />}</small>
        </div>

Solution

  • You can use the style prop to add a CSS transform to rotate the icon with a CSS transition to animate the transition.

    const style = {
     transform: show ? 'rotate(180deg)' : '', 
     transition: 'transform 150ms ease', // smooth transition
    }
    
    <div className="col-2 d-flex align-items-center">
     <small><CaretUpFill style={style}/></small>
    </div>
    
    //if the icon doesn't have access to style props you can add it to the <small> element
    <div className="col-2 d-flex align-items-center">
     <small style={style}><CaretUpFill /></small>
    </div>
    

    You could also use a third party library like Framer Motion to animate your components - but it is overkill for your needs.