Thomas Mannion
Thomas Mannion

Reputation: 61

React Draggable stopping onClick for Child component

I am trying to create draggable cards that can also flip over on click.

This is my card

import { useState } from 'react'
import './Card.scss'

function Card() {
  const [flip, setFlip] = useState(false)

  return (
      <div className={`card ${flip ? "flip" : ""}`}>
        <div className="front" onClick={()=>{setFlip(!flip)}}>
          <h1>Front</h1>
        </div>
        <div className="back" onClick={()=>{setFlip(!flip)}}>
          <h1>Back</h1>
        </div>
      </div>
  )
}

export default Card

This is the Draggable wrapper for the Card

import Draggable from 'react-draggable'
import Card from './Card'

function DraggableCard() {
  return (
    <Draggable>
      <div>
        <Card />
      </div>
    </Draggable>
  )
}

export default DraggableCard

This is the CSS that is supposed to trigger onClick for the Card to flip

.card {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border-radius: 20px;
  transform: perspective(1000px) rotateY(var(--rotate-y, 0deg))
    translate(var(--translate-y, 0))
    rotate(var(--rotate, 0deg));
  transition: transform 0.7s;
  transform-style: preserve-3d;
  cursor: pointer;
  height: 300px;
  width: 200px;
  background-color: rgb(219, 14, 14);
}

.front {
  position: absolute;
}

.back {
  position: absolute;
  transform: rotateY(180deg);
}

.front, .back {
  height: 100%;
  width: 100%;
  backface-visibility: hidden;
  transition: transform 1s;
}

.card.flip {
  --rotate-y: -180deg;
}

The onClick handler in the Card should change the useState for "flip" and then, in turn, alter the className from "card" to "card flip" this should then trigger the CSS to flip the card. I can see that the className is not changing on click.

I saw that the Draggable README talked about using

Use an intermediate wrapper (<Draggable><span>...</span></Draggable>) in this case.

I added the extra <div> around the Card component in DraggableCard, but it did not seem to change the outcome. Did I miss understanding the README from react-draggable?

I assume that it is being overridden by the Draggable component but am struggling to figure out how not to let this happen.

Upvotes: 6

Views: 463

Answers (1)

adrilasar
adrilasar

Reputation: 61

Looks like onClick or onChange inside <Draggable> are disabled on mobiles (or on touch devices in general).

To make elements inside the drag component clickable, set as cancel the selector of those elements.

<Draggable cancel="button, a">
  <div>
    ...
    <button>click</button>
    <a>link</a>
  </div>
</Draggable>

Upvotes: 0

Related Questions