Friday, August 18, 2023

React : window.scrollTo or move page to a position

 

Certainly, if you want to use `window.scrollTo` or equivalent methods to scroll the page, here are some examples:

 

1. **Using `window.scrollTo` with Coordinates**:

 

```tsx

const scrollToPosition = (yPosition: number) => {

    window.scrollTo({ top: yPosition, behavior: 'smooth' });

};

// Example usage

scrollToPosition(500); // Scroll to y position 500

```

In this example, `window.scrollTo` is used to scroll to a specific y-position on the page. The `behavior: 'smooth'` option provides smooth scrolling.

2. **Using Element's `scrollIntoView` Method**:

```tsx

const scrollToElement = (elementId: string) => {

    const element = document.getElementById(elementId);

    if (element) {

        element.scrollIntoView({ behavior: 'smooth' });

    }

};

// Example usage

scrollToElement('myTargetElement'); // Scroll to element with id "myTargetElement"

```

In this example, the `scrollIntoView` method is used on an HTML element with a specified ID. The element will be scrolled into view with smooth scrolling.

 

3. **Using `scrollTo` or `scrollBy` on Specific Element**:

 

```tsx

const scrollToElement = (elementId: string, yOffset: number = 0) => {

    const element = document.getElementById(elementId);

    if (element) {

        const yPosition = element.getBoundingClientRect().top + window.pageYOffset + yOffset;

        window.scrollTo({ top: yPosition, behavior: 'smooth' });

    }

};

// Example usage

scrollToElement('myTargetElement', -100); // Scroll to element with id "myTargetElement" with a yOffset of -100 pixels

```

In this example, `getBoundingClientRect` is used to calculate the y-position of an element relative to the viewport. You can adjust the yOffset to fine-tune the scrolling position.

Remember that smooth scrolling behavior might not work in all browsers or under all circumstances. It's generally supported in modern browsers. If smooth scrolling doesn't work as expected, you can use the default behavior by omitting the `behavior` option or replacing `'smooth'` with `'auto'`.

No comments:

Post a Comment