최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday

티스토리 뷰

 

simplebar-react - npm (npmjs.com)에서 제공하는 라이브러리를 사용할 때, 스크롤을 세로 가운데 정렬 구현.

 

dom에 대한 참조는 크게 2가지 방법이 있다.

 

1. scrollableNodeProps를 useRef로 사용하여 참조하는 방법

scrollableNodeProps

You can pass props to the underlying scrollable div element. This is useful for example to get a ref of it, if you want to access the scroll event or apply imperative directive (like scrolling SimpleBar to the bottom, etc.).

const scrollableNodeRef = React.createRef();

<SimpleBar scrollableNodeProps={{ ref: scrollableNodeRef }}>
  // your content
</SimpleBar>;

 

2. 또는 컴포넌트를 직접 참조하여  getScrollElement()getScrollElement()로 접근할 수 있다.

Trigger programmatical scrolling

If you want to access to the original scroll element, you can retrieve it via a getter:

const simpleBar = new SimpleBar(document.getElementById('myElement'));
simpleBar.getScrollElement();

Subscribe to scroll event

You can subscribe to the scroll event, just like you do with native scrolling elements:

const simpleBar = new SimpleBar(document.getElementById('myElement'));
simpleBar.getScrollElement().addEventListener('scroll', function(...));

 

1번 혹은 2번을 통해 가져오는 결과는 모두 같으며, 스크롤 높이를 계산할 때 가져오는 박스는 다음을 참고해야 한다.

mask영역이 아닌 순수 스크롤되는 박스의 크기는 scrollHeight 값과 같다.

따라서 아래에 작성한 샘플 코드에서는 세로 중앙정렬을 위해서 scrollHeight 속성을 가져왔으며,
스크롤을 세로 가운데 정렬하기 위해서는 SimpleBarReact 컴포넌트(scrollHeight)에서 masking 되는 height의 높이 값을 빼준 뒤,
반으로 나누면

 

 

 

 

 

 

 

 

 

 

* 이미지 출처: scrollHeight, clientHeight, offsetHeight 의 차이 (tistory.com)

 

 

 

 

 

 

댓글