[react-beautiful-dnd] react, next.js 드래그 만들기 2

 

[react-beautiful-dnd] react, next.js 드래그 만들기 2

[react-beautiful-dnd] react, next.js 드래그 만들기 1 [react-beautiful-dnd] react, next.js 드래그 만들기 1 # react-beutiful-dnd 요소를 통한 Drag 만들기 github.com/atlassian/react-beautiful-dnd atlass..

minaminaworld.tistory.com

# 결과화면 


 

1.  index.js

 - DragLand Component 불러오기

import DragLand from "../components/DragComponent/DragLand"
// import Test from '../components/Test'

const Index = () => {
    return (
        <>
            <div>Hello next.js 10</div>
            <br/>
            {/* Drag Component */}
            <DragLand></DragLand>
        </>
    )
}

export default Index;

 

2.  DragLand.js

 -DragLand.js ComponentLoad된 시점 Drag Components 불러오기

// React 관련 요소
import React, { useCallback, useEffect, useState, PureComponent } from 'react';
import Drag from './Drag';

const DragLand = () => {
    // window가 로드 된 시점에서 렌더링
    const [winReady, setwinReady] = useState(false);
    useEffect(() => {
        setwinReady(true);
    }, []);

    return (
        <>
            {/* 윈도우, DOM 로드 시점에서 드래그 생성 */}
            {winReady ? <Drag /> : null}
        </>
    );
};

export default DragLand;

3.  Drag.js

 -Drag 요소 만들기

// React 관련 요소
import React, { useCallback, useEffect, useState, PureComponent } from 'react';
// 드래그 요소
import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd';
// 스타일 정의 
import styled from 'styled-components';
import '@atlaskit/css-reset';

const DragContent = styled.div`
  border: 1px solid lightgrey;
`;

const Content = styled.div`
  margin: 8px;
  padding : 10px;
  border: 1px solid lightgrey;
  border-radius: 2px;
`;

// 드래그 요소 생성 
const Drag = () => {
    const [datas, setDatas] = useState([
        { key: 'item-1', content: 'item-1' },
        { key: 'item-2', content: 'item-2' },
        { key: 'item-3', content: 'item-3' },
        { key: 'item-4', content: 'item-4' },
    ]);

    const onDragEnd = (result, provided) => {

        if (!result) {
            console.log('result가 null인 경우');
            return;
        }

        // 드래그 결과
        // source : 원본 
        // destination : 변경 
        const { destination, source } = result;

        // 동일한 위치에서 놓은 경우 
        if (destination.index === source.index) {
            console.log('초기 위치 index 동일한 경우');
            return;
        }

        // 데이터 변경
        setDatas((prev) => {
            // 원본 데이터 
            const sourceData = datas[source.index];
            // datas 복사
            let newDatas = prev;
            // 기존 데이터 제거 
            newDatas.splice(source.index, 1);
            // 이동 위치로 데이터 옮기기
            newDatas.splice(destination.index, 0, sourceData);

            return newDatas;
        });

    };

    return (
        <>
            {/* 드래그 영역 */}
            <DragDropContext
                onDragEnd={onDragEnd}
            >
                {/* 드래그 놓을 수 있는 영역 */}
                <Droppable droppableId="DropLand">
                    {/* 드래그 Div 생성 */}
                    {(provided, snapshot) => (
                        // CCS가 적용된 Div
                        <DragContent
                            {...provided.droppableProps}
                            ref={provided.innerRef}
                        >
                            <p>Drag Div!</p>
                            {datas.map((data, index) => (
                                <Draggable key={data.key} draggableId={data.key} index={index}>
                                    {(provided, snapshot) => (
                                        <Content
                                            ref={provided.innerRef}
                                            {...provided.draggableProps}
                                            {...provided.dragHandleProps}
                                        >
                                            {data.content}
                                        </Content>
                                    )}
                                </Draggable>
                            ))}
                            {provided.placeholder}
                        </DragContent>
                    )}
                </Droppable>
            </DragDropContext>
        </>
    )
}

export default Drag;

 

블로그 이미지

미나미나미

,

 

[react-beautiful-dnd] react, next.js 드래그 만들기 1

 

[react-beautiful-dnd] react, next.js 드래그 만들기 1

# react-beutiful-dnd 요소를 통한 Drag 만들기 github.com/atlassian/react-beautiful-dnd atlassian/react-beautiful-dnd Beautiful and accessible drag and drop for lists with React - atlassian/react-beau..

minaminaworld.tistory.com


1.   npm i styled-components

   - css 적용하기 위해서 설치 

2.  npm i react-beautiful-dnd

    - drag을 위해서 설치 

3. npm i @atlaskit/css-reset

   - drag 생성할 때, 필요한 요소라고 함. (공식 문서에서 추가 요소)

 

사용 방법

4. package.json

   - 설치된 요소

블로그 이미지

미나미나미

,

# react-beutiful-dnd 요소를 통한 Drag 만들기

github.com/atlassian/react-beautiful-dnd

 

atlassian/react-beautiful-dnd

Beautiful and accessible drag and drop for lists with React - atlassian/react-beautiful-dnd

github.com


1. package.json 생성 

2. react 요소 설치

 



3. next 설치 

4. next 실행

블로그 이미지

미나미나미

,

# 에러 상황

  - Next.js에서 react-beautiful-dnd을 적용할 때, 드래그가 제대로 동작하지 않은 경우.   

 

package.json

 

 

# 문제점 

 - 문제가 되는 이유는 컴포넌트가 로드 되기 전, DOM, Window가 먼저 로드되지 않는 상황이라고 판단됨.

 

 

 # 해결 방안 

 

  - useEffect를 통해서 Window, DOM이 렌더링 된 시점에서 드래그 요소 렌더링.

 

# 결과화면 

 

블로그 이미지

미나미나미

,

 

# RegBean.java

package com.example.demo;

public class RegBean {

    private String beanName;
    private int beanInt;

    public void setBeanInt(int beanInt) {
        this.beanInt = beanInt;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public int getBeanInt() {
        return beanInt;
    }

    public String getBeanName() {
        return beanName;
    }

    @Override
    public String toString() {
        return "RegBean{" +
                "beanName='" + beanName + '\'' +
                ", beanInt=" + beanInt +
                '}';
    }
}

# RegBeanConfiguration.java

@Configuration
@EnableConfigurationProperties(RegBeanProperties.class)
public class RegBeanConfiguration {

    @Bean
    @ConditionalOnMissingBean // 이 타입에 Bean 없을 때만 등록
    public RegBean regBean(RegBeanProperties properties) {
        RegBean regBean = new RegBean();
        regBean.setBeanInt(properties.getBeanInt());
        regBean.setBeanName(properties.getBeanName());
        return regBean;
    }
}

# RegBeanProperties.java

pom.xml에 등록해야함.

 

// 소문자 가능함.
@ConfigurationProperties("reg-bean")
public class RegBeanProperties {

    private String beanName;
    private int beanInt;

    public void setBeanInt(int beanInt) {
        this.beanInt = beanInt;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public int getBeanInt() {
        return beanInt;
    }

    public String getBeanName() {
        return beanName;
    }

}

# Maven Install


 

1. pom.xml 특정 jar 가져오기

        <dependency>
            <groupId>com.example</groupId>
            <artifactId>AutoconfigurationSub</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

 

2.  가져온 Bean 값 활용하기 

@Component
public class RegBeanRunner implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(RegBeanRunner.class);

    @Autowired
    RegBean regBean;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        logger.info("regBean=" + regBean.toString());
    }
}

 

3. application.properties에서 프로퍼티즈 등록하기 

logging.level.root=debug
reg-bean.beanInt=10
reg-bean.beanName=RegBeanTest

 

4. 결과 

 

 

블로그 이미지

미나미나미

,