I have a problem where I'm trying to create a memory game grid and when I click on a grid item it opens up. Currently I have a working grid but I've only managed to work it with hover, and don't understand how to make it work with click event when the state changes.
Basically my grid item code tree is
<Box onClick={this.handleOpenCard}>
<Front />
<Back>
<img src="" alt="" />
</Back>
</Box>
What I want to do is when I click on card I change component state open
to true
. And when this state is true I want with styled-components perform the css animation which rotates card to 180deg.
Please see full component code where currently works when I hover on item, please give me ideas how to achieve that or maybe refactor code.
import React, { Component } from "react";
import styled from "styled-components";
const Box = styled.div`
position: relative;
perspective: 1000px;
`;
const Front = styled.div`
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
display: flex;
justify-content: center;
align-items: center;
transition: 1s;
backface-visibility: hidden;
border-radius: 10px;
background-color: #fff;
cursor: pointer;
${Box}:hover & {
transform: rotateY(180deg);
}
img {
width: 100%;
max-width: 75px;
}
`;
const Back = Front.extend`
background-color: #ffeb3b;
transform: rotateY(180deg);
${Box}:hover & {
transform: rotateY(0deg);
}
`;
class Card extends Component {
state = {
open: false
};
handleOpenCard = e => {
this.setState({ open: true });
};
render() {
return (
<Box open={this.state.open} onClick={this.handleOpenCard}>
<Front />
<Back>
<img
src={
process.env.PUBLIC_URL +
`/images/svg/${this.props.path}`
}
/>
</Back>
</Box>
);
}
}
export default Card;
You can access props in styled-components very easily.
In your Box: transform: ${props => props.open ? rotateY(180deg) : rotateY(0deg)}
To pass props to children:
Front = styled.div`
`
Box = styled.div`
${Front} {
transform: ${props => props.open ? rotateY(180deg) : rotateY(0deg)}
}
`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With