리액트 컴포넌트 드래그로 위치 이동하기 (react-use-gesture + react-spring)

정수현·2023년 2월 16일
26

React

목록 보기
1/8

필요한 모듈 설치

react-use-gesture

  • 제스처를 통한 UI 상호작용을 구현할 수 있는 라이브러리이다.
  • react-use-gesture
  • 설치
    npm i react-use-gesture --save

react-spring

  • spring-physics 기반의 애니메이션 라이브러리이다.
  • react-spring
  • 설치
    npm i react-spring --save

드래그 가능한 컴포넌트 만들기

import { useDrag } from "react-use-gesture"
import { useSpring, animated } from 'react-spring';

function App() {
  	// 초기 값
	const pos = useSpring({x:0, y:0});
  
    const bindPos = useDrag((params)=>{
      // offset = [xoffset, yoffset]
      // 초기 위치로부터 떨어진 값
      pos.x.set(params.offset[0]);
      pos.y.set(params.offset[1]);
    });
  
  return (
    // animated.div는 react-spring에서 제공
    <animated.div {...bindPos()} style={{
          x: pos.x,
          y: pos.y
      }}>
      
	// 컴포넌트에 들어갈 내용
    //  ...
      
    </animated.div>
  )
}

useDrag 훅은 이벤트 핸들러가 있는 함수를 반환한다. {...bindPos()}는 스프레드 문법으로 컴포넌트로 들어가는데 실제로는 onMouseDownonTouchStart이벤트가 추가되는 것이다.

드래그 가능한 컴포넌트를 만드는 DragContainer 컴포넌트 만들기

드래그 가능한 컴포넌트를 여러 개 생성할 것이기 때문에, 컨테이너 컴포넌트를 만들어서 재사용하고자 했다.

// DragContainer.jsx

import React from 'react'
import { useSpring, animated } from 'react-spring';
import { useDrag } from 'react-use-gesture';

export default function DragCont(props) {
  const pos = useSpring({x:0, y:0});
  const bindPos = useDrag((params)=>{
    pos.x.set(params.offset[0]);
    pos.y.set(params.offset[1]);
  });

  return (
    <animated.div {...bindPos()} style={{
          x: pos.x,
          y: pos.y
      }}>
      // <DragContainer></DragContainer> 내부에 전달된 자식 컴포넌트를 넣어주기 위해 props.children 사용
      {props.children}
      
    </animated.div>
  )
}

DragContainer 컴포넌트 사용하기

import React from 'react'
import DragCont from '../DragCont'

export default function DesktopIcon(props) {
    return (
        <DragCont>
        	// 드래그로 움직이고 싶은 요소 시작
            <div>
                <img src="" alt=''/>
                <span>텍스트</span>
            </div>
        	// 드래그로 움직이고 싶은 요소 끝
        </DragCont>
    )
}

DragCont(DragContainer) 컴포넌트를 불러오고, 드래그를 통해 위치를 조절하게 할 컴포넌트 전체를 DragCont로 감싸준다.
끝!

결과


컴포넌트를 드래그 하면 위치가 이동한다!😋
렌더링 될 때마다 초기 상태로 돌아간다.

6개의 댓글

comment-user-thumbnail
2023년 2월 17일

오늘도 좋은 글 잘 봤습니다! 항상 결과물을 시각적으로 잘 보여주셔서 이해가 잘 될 수 있었어요! 좋은 하루 되세요 :)

1개의 답글
comment-user-thumbnail
2023년 2월 20일

우와아..! 수현님 저 멋진 비밀일기는 먼가여

1개의 답글
comment-user-thumbnail
2023년 2월 21일

이미지 감성 보고 읽고 갑니다 ㅋㅋ

1개의 답글