Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling onClick with React styled-components

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;
like image 991
Sangsom Avatar asked Nov 07 '22 05:11

Sangsom


1 Answers

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)}
    }
`
like image 150
NiftyAsp Avatar answered Nov 15 '22 05:11

NiftyAsp