Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add useScrollTo #185

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export { useRenderCount } from './useRenderCount/useRenderCount';
export { useRenderInfo } from './useRenderInfo/useRenderInfo';
export { useRerender } from './useRerender/useRerender';
export { useScript } from './useScript/useScript';
export { useScrollTo } from './useScrollTo/useScrollTo';
export { useSessionStorage } from './useSessionStorage/useSessionStorage';
export { useSet } from './useSet/useSet';
export { useShare } from './useShare/useShare';
Expand Down
31 changes: 31 additions & 0 deletions src/hooks/useScrollTo/useScrollTo.demo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { useScrollTo } from "@/hooks/useScrollTo/useScrollTo";

const blockStyle = {
border: '1px solid gray',
height: 300,
width: 300,
}

const Demo = () => {
const {targetToScroll, scrollToTarget} = useScrollTo<HTMLDivElement>();

const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault();
event.stopPropagation();
scrollToTarget();
};


return (
<>
<button onClick={handleClick}>Scroll to block 3</button>
<div style={{overflow: 'auto', height: '320px', position: 'relative' }}>
<div style={blockStyle}>Block 1</div>
<div style={blockStyle}>Block 2</div>
<div ref={targetToScroll} style={blockStyle}>Block 3</div>
</div>
</>
)
}

export default Demo
47 changes: 47 additions & 0 deletions src/hooks/useScrollTo/useScrollTo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { act, renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';

import { useScrollTo } from './useScrollTo';

describe('useScrollTo', () => {
it('should define scrollTo and targetRef', () => {
const { result } = renderHook(() => useScrollTo());

expect(result.current.scrollToTarget).toBeDefined();
expect(result.current.targetToScroll).toBeDefined();
});

it('should scroll to target element', () => {
const { result } = renderHook(() => useScrollTo());
const scrollIntoViewMock = vi.fn();

const mockElement = document.createElement('div');
mockElement.scrollIntoView = scrollIntoViewMock;

act(() => {
(result.current.targetToScroll as React.MutableRefObject<HTMLElement | null>).current =
mockElement;
});

act(() => {
result.current.scrollToTarget();
});

expect(scrollIntoViewMock).toHaveBeenCalledWith({
behavior: 'smooth',
block: 'nearest',
inline: 'nearest'
});
});

it('should not scroll if targetRef is not set', () => {
const { result } = renderHook(() => useScrollTo());
const scrollIntoViewMock = vi.fn();

act(() => {
result.current.scrollToTarget();
});

expect(scrollIntoViewMock).not.toHaveBeenCalled();
});
});
56 changes: 56 additions & 0 deletions src/hooks/useScrollTo/useScrollTo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { useRef } from 'react';

const OPTIONS_DEFAULT: ScrollIntoViewOptions = {
/**
* Defines the transition animation.
* One of 'auto' or 'smooth'.
*
* @default 'smooth'
*/
behavior: 'smooth',
/**
* Defines vertical alignment.
* One of `'start'`, `'center'`, `'end'`, or `'nearest'`
*
* @default 'nearest'
*/
block: 'nearest',
/**
* Defines horizontal alignment.
* One of `start`, `center`, `end`, or `nearest`. Defaults to nearest.
*
* @default 'nearest'
*/
inline: 'nearest'
};

interface UseScrollToReturn<T extends HTMLElement> {
targetToScroll: React.RefObject<T>;
scrollToTarget: () => void;
}

/**
* @name useScrollTo
* @description Hook that provides a function to smoothly scroll to a target element.
*
* @param {ScrollIntoViewOptions} [options=OPTIONS_DEFAULT] - Options for the scrollIntoView method.
*
* @returns {Object} An object containing the reference to the target element and the function to scroll to it.
* @returns {React.RefObject<T | null>} targetToScroll - The ref object to be attached to the element you want to scroll to.
* @returns {function} scrollToTarget - The function to call to scroll to the target element.
*
* @example
* const { targetToScroll, scrollToTarget } = useScrollTo();
*/
export const useScrollTo = <T extends HTMLElement>(
options: ScrollIntoViewOptions = OPTIONS_DEFAULT
): UseScrollToReturn<T> => {
const targetToScroll = useRef<T | null>(null);

const scrollToTarget = () => {
if (!targetToScroll.current) return;
targetToScroll.current.scrollIntoView(options);
};

return { targetToScroll, scrollToTarget };
};