Issue
I have React component Card which has a parent div with two divs inside (front-side and back-side of card) and a button below the parent div. And what I want is to rotate them on button click. I did it with hover and transform but I'm struggling to make that work on button click.
Basically, it should rotate them for 180 deg on each click. Any ideas?
code structure:
function Card(){
return(
<>
<div className="parent">
<div className="front-side">
<div/>
<div className="back-side">
<div/>
</div>
<button onClick={ }>Rotate</button>
</>
)
}
Thanks!
EDIT:
css:
.front,.back{
border: 1px solid black;
width: 300px;
height: 440px;
overflow: hidden;
backface-visibility: hidden;
position: absolute;
transition: transform .6s linear;
}
.front {
background: whitesmoke;
transform: perspective(600px) rotateY(0deg);
}
.back{
background: skyblue;
transform: perspective(600px) rotateY(-180deg);
}
.card:hover > .front{
transform: perspective(600px) rotateY(180deg);
}
.card:hover > .back{
transform: perspective(600px) rotateY(0deg);
}
Solution
Use local state to save rotation state and simply re-write your css using classes, instead of pseudo classes.
function Card(){
const [isRotated, setIsRotated] = React.useState(false);
const onRotate = () => setIsRotated((rotated) => !rotated);
return(
<div className={`card ${isRotated ? 'rotated' : ''}`} onClick={onRotate}>
<div className="front">
</div>
<div className="back">
</div>
</div>
); }
And change your css like this:
.card.rotated > .front{
transform: perspective(600px) rotateY(180deg);
}
.card.rotated > .back{
transform: perspective(600px) rotateY(0deg);
}
I created a sample on codepen, please check it - https://codepen.io/fadetoblack1/pen/zYoxNXx
Answered By - Vlad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.