React - 한 부모를 가진 자식끼리 이벤트 주고받아서 Element 컨트롤하기 (useRef, forwardRef, useImperativeHandle)

0

React

목록 보기
8/9

React 페이지네이션 작업 중,
페이지 버튼을 클릭해서 새로운 데이터가 뿌려지며 스크롤 상단으로 이동하는 이벤트를 작업하고 싶었다.

디지버지게 두세시간 죽쑤고 찾아낸 방법은 아래와 같다.

Parent.jsx

// Parent.jsx
import { useRef } from 'react';
import { Page } from '...page';
import { Pagination } from '...Pagination';

const Parent = () => {
  const scrollPageRef = useRef(null);
  const sendEvent = () => {
    scrollPageRef.current.moveScroll();
    // Page 컴포넌트에서 moveScroll 이벤트 실행
  }
  return (
    <Layout>
      <Page ref={scrollPageRef}>
    	...
      </Page>
      <Pagination ... sendEvent={sendEvent}/>
	</Layout>
);

Pagination.jsx

// Pagination.jsx
function Pagination({ ... sendEvent }) {
  const handlePage = () => {
      ... // 페이지 이동 스크립트
      sendEvent(); // Parent 컴포넌트에서 실행
  }

  return (
    <Nav>
      ...
      <Button ... onClick={() => handlePage()} />
      ...
    </Nav>
  );
}

Page.jsx

// Page.jsx
import { useRef, forwardRef, useImperativeHandle } from 'react';
const Page = forwardRef((props, ref) => {
  const scrollRef = useRef(null);
  useImperativeHandle(ref, () => ({
    moveScroll: () => { // scroll 최상단으로 이동하는 함수
      scrollRef.current.scrollTo(0, 0);
    }
  }));
  return (
    <PageWrap >
      <PageContents ref={scrollRef}> // 스크롤영역 overflow-y: auto
        {props.children}
      </PageContents>
    </PageWrap>
  );
});

위와 같이 설정해주니 정상 작동한다.

그러나 더 쉬운 방법이 있었다.

Page 컴포넌트에서 스크롤 영역에 styled components로 id를 주고
pagination 컴포넌트 내에서 이벤트를 처리하는 방법도 있었다.
말 그대로 뻘짓 한거임. 아니야... 많은 배움이 되었습니다.
배울 수 있어 행복합니다.😀

profile
를 질투하는 그냥 개발자입니다.

0개의 댓글