user15566087
user15566087

Reputation:

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>

Upvotes: 3

Views: 27746

Answers (4)

Marcos Berrutto
Marcos Berrutto

Reputation: 21

You can use "rotate" function with CSS, this is the easiest way:

style={{ transform: 'rotate(180deg)' }}

Upvotes: 1

ChilTest
ChilTest

Reputation: 511

I recommend you framer-motion library You can rotate elements, and do a lot of manipulations. Which difference between css and framer motion? Motion its js components, working fine

Here is example

Upvotes: 0

Sean W
Sean W

Reputation: 6658

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.

Upvotes: 10

mymoto
mymoto

Reputation: 341

use css property:

transform: rotate(180deg)

I see that you've created two elements - <CaretUpFill /> and <CaretDownFill />.

What you're doing now is basically unmounting the <CaretUpFill /> and mounting the <CaretDownFill /> component (and vice versa), but to my knowledge it's impossible to create an animation between two separate components.

Therefore, I recommend using just one component, and adding an animation by using the css property above.

Upvotes: 0

Related Questions