This video is available to students only
Implementing Scroller
Writing code for the Scroller library and exporting it for users.
Writing a hook#
Open up the Scroller directory and navigate to the src
directory. Create a new file called useScroller.js
. Enter the following code:
1
/**
2
* A hook which manages scrolling.
3
*
4
* {options} expects: { x: number, y: number, isSmooth: boolean }.
5
*/
6
export function useScroller({ x, y, isSmooth = false }) {
7
// Check if `window` exists.
8
// This function can run in NodeJS which doesn't have a global `window` variable.
9
// NodeJS is required for unit testing.
10
if (!window) {
11
return;
12
}
13
14
return function scroller() {
15
// Modern browsers provide a scrolling interface!
16
window.scrollTo({
17
left: x,
18
top: y,
19
behavior: isSmooth ? "smooth" : "auto",
20
});
21
};
22
}
Let's break down what each line of the code above is doing. We'll start by exporting a function called useScroller
which takes an options object which will tell us where to scroll to in the x/y coordinates, and if we should scroll smoothly.
React defines a few rules and best practices when using hooks. One common practice is to name a hook starting with use
.
This page is a preview of Creating React Libraries from Scratch