[TIL] 특정 DOM 의 크기 가져와 사용하기

Solmin Seo·2020년 11월 27일
0
post-thumbnail

어떠한 포스트를 열면 드롭다운 형식으로 내려오게 되는 UI를 개발하는 과정에서 퍼센테이지가 작동하지 않고(설계상의 문제일 수도 있다) 오로지 px로 값을 설정해야 애니메이션이 작동 될 때가 있다.

특정 DOM의 정보를 가져오는 작업을 진행해야할 때 참고하려 작성해두는 포스트입니다.

code

 <div className="wrapper">
      <animated.div className="headerContainer" onClick={(e) => onClick(e)}>
        <div className="type">{type}</div>
        <p className="title">{item.title}</p>
        <div className="formattedDate">{item.createAt.split(' ')[0]}</div>
        <animated.img style={arrowAnimation} src="/image/up.png" />
      </animated.div>

      <animated.div style={collapseAnimation} className="contentContainer">
          <div className="title">{item.title}</div>
          <div dangerouslySetInnerHTML={{ __html: item.content }} className="content" />
      </animated.div>
    </div>

실질적으로 작동할때에는 headerContainer를 클릭하면 아래에 contentCotainer가 dropdown 처럼 아래로 촤라락하고 나오는 기획이다.

만일 header를 클릭하였을때에 아래의 contentContainer의 height값을 유동적으로 가져와 애니메이션에 적용할 수 있다면 content의 크기가 어떻든 대응이 가능하며 조금 더 유연한 기능이 될 거라 생각하여 작업을 진행해보았다.

1.headerContainer 클릭
2.contentContainer의 height를 가져오기
3.from (contentContainer의 height)px to 0px animation 처리

애니메이션 코드

  const openAnimation = useSpring({
    height: isOpen ? `${sampleHeight}px` : '0px',
  });

onClick

  const onClick = (e: any) => {
    sampleHeight(e.currentTarget.parentElement.children[1].children[0]?.offsetHeight);
    isOpen(!isOpen);
  };

온클릭 이벤트가 일어날 때에 해당 DOM의 높이를 가져와 animation에 할당해주어 컨텐츠의 길이에 맞게 유동적으로 적용한다.

profile
코린이

0개의 댓글