How to make scroll bar start from the top in every page - javascript

who could help me out?
In my react app, I have 3 pages
1.Homepage
2.Settings page
3.Profile page
When I scroll down in the homepage and I navigate to the profile or settings page, it displays the bottom of these next pages corresponding to where I left the scroll bar in the homepage.
How do I stop react from remembering the scroll point when I navigate.

To scroll to the top, include useEffect() that will scroll the page to the top when that component loads. Include this on each page that you want to scroll to the top on load.
import { useEffect } from "react";
export const Homepage = () => {
useEffect(() => window.scrollTo(0, 0), []);
return (<>Hello, world!</>)
}
Note that the second parameter of useEffect can take a variable so that it runs whenever that variable changes. This could allow you to include this code on a higher-level component that watches for page changes.
useEffect(() => window.scrollTo(0, 0), [page]);

Related

One more automatically Re-render in React

In my React project I use scrolling function to go to the same scroll position after coming back from user page (using scroll ref in div), but when page reloads scroll doesn't go to position, but if I'll mechanically re-render page, it goes to the defined position. So I need one more re-render page to scroll it to position, but should be automatically and not after manually on click. anyone can help how can I fix this issue?
// go back to saved scroll position
const Scrolling = () => {
const pos = localStorage.getItem("webLocal:scrollPosition");
const w = document.getElementById("feed");
return (w.scrollTop = pos);
};
useEffect(() => {
Scrolling();
}, [userList]);
I tried lot of ways, setInterval, useEffect, useMemo etc. with all possible dependencies..

Showing & Hiding Navbar Bug on Momentum-Based Touch Devices

I used the code below to add a simple navbar hiding and showing when a user scrolls up and down on a webpage.
const Navbar = () => {
const [show, setShow] = useState(true);
const [lastScrollY, setLastScrollY] = useState(0);
const controlNavbar = () => {
if (typeof window !== 'undefined') {
if (window.scrollY > lastScrollY) { // if scroll down hide the navbar
setShow(false);
} else { // if scroll up show the navbar
setShow(true);
}
// remember current page location to use in the next move
setLastScrollY(window.scrollY);
}
};
useEffect(() => {
if (typeof window !== 'undefined') {
window.addEventListener('scroll', controlNavbar);
// cleanup function
return () => {
window.removeEventListener('scroll', controlNavbar);
};
}
}, [lastScrollY]);
return (
<nav className={`active ${show && 'hidden'}`}>
....
</nav>
);
};
export default Navbar;
It works perfectly well on a desktop browser, but had a bug when testing it on my iphone (on both chrome and safari). On touch devices, when scrolling back to the top, there's a little bounce animation where the scroll goes past the top of the page and then rubberbands back to the actual top of the page. This behaviour causes my event listener to register that the user scrolled down, and hides the navbar. Similarly, when the user scrolls to the bottom of the page, the rubberband effect causes my navbar event listener to register that the user scrolled up (when it bounces back) and shows the navbar. I hope I'm explaining this clearly (lol).
I'm trying to think of a solution, and the best one I came up with is to set the hiding and showing behaviour to work after a scroll of a certain number of pixels, so something like this.
if (window.scrollY > lastScrollY + 20){
follow abovementioned logic...
}
But since the bounce amplitude is based on the user's scroll speed, if the user scrolls really aggressively to the top of the window it definitely is going to bounce more than 20 pixels and therefore the same bug occurs.
I can't seem to even find others facing this problem online, so any help would be appreciated!

Scroll to id not working in Fullscreen mode

I have created a script to enable/disable the full screen in web page (React JS). On the web page on click button web page scrolls to top. Scroll to top is working fine in normal web page but when full screen is enabled scroll is not working.
Also, I used the scrollToElement React JS package for scrolling but this is also not working.
import React from 'react';
import {FullScreen, useFullScreenHandle}
export const A = () => {
/* Click handler to enable the scroll to root*/
handleClick = () => {
window.scrollTo( 0, 0)
}
return (<FullScreen handle={handle}>
<button onclick={ () => handleClick() }>Scroll To Top</button>
</FullScreen>)
}
In Fullscreen scroll is not working.
The third-party library used react-full-screen has an implementation where when the FullScreen Component goes to fullscreen it sets the containing div to height: 100% without overflow: auto/scroll.
Thus, the element takes the fullscreen and the content overflows without scroll. So, we need to set the overflow correctly and set the scroll function to the containing div instead of body.
This div is the containing element when fullscreen is activated over it by the package.
Check out the implementation here. Open the preview in a new tab for fullscreen to work properly.

How can I use React hooks to respond to a prop change before render

I am trying to use a functional component and React hooks to implement a simplified auto-scroller that will automatically scroll a container to the bottom when the child content overflows. But the auto-scrolling should only happen when the scrollbar is already enar the bottom (e.g., if the user has scrolled up to look at output, the scroll position should not change when new content comes in).
I know how to implement the auto-scrolling behavior by using refs and performing computation on clientHeight, scrollTop, and scrollHeight.
The problem I have is that I need to compute a shouldAutoScroll() check BEFORE the component is re-rendered.
My flow needs to look like this:
<container>
{props.children}
</container>
When props.children changes:
1. Check if the scrollbar is near the bottom and store the result
2. Update container to reflect the new props.children
3. If the check from step 1 is true, scroll to the bottom
I can't seem to find a way to to this using useEffect and/or useLayoutEffec. When using these what happens is:
1. Scroll position is at bottom
2. props.children updates with new items
3. <container> is rerendered, pushing the scrollbar up
4. The checkScrollBarBottom() method is called and returns false
5. The scrollbar is not auto-scrolled
I need to keep the component generic, so that it can auto scroll regardless of what type of component or element props.children is. In some cases the change to props.chldren might be a single line. In others, it might be 20 lines, or it might be an image.
If I were using an older-style class component, I could do the computation in componentWillReceiveProps(). How do I replicate this with hooks?
I discovered one solution that works, but seems a little messy.
The solution is to calculate and update shouldAutoScroll() during the container's onScroll() event. This seems messy because I am capturing a ton of useless intermediate scroll information, when all I care about is the scroll position at the moment the update starts (but before the component is re-rendered).
Full code:
import React, { useRef, useEffect, useLayoutEffect } from 'react';
import styles from './AutoScroller.module.scss';
export function AutoScroller({children, className=''}) {
const classNames = `${styles.default} ${className}`;
const containerRef = useRef(null);
const shouldAutoScroll = useRef(false);
function updateShouldAutoScroll(element, tolerance) {
const {scrollHeight, scrollTop, clientHeight} = element;
const result = scrollHeight - scrollTop <= clientHeight + tolerance;
shouldAutoScroll.current = result;
}
function onContainerScroll(e) {
updateShouldAutoScroll(e.target, 25)
}
useEffect(function autoScroll() {
if (shouldAutoScroll.current) {
const element = containerRef.current;
element.scrollTop = element.scrollHeight;
}
});
return (
<div className={classNames} ref={containerRef} onScroll={onContainerScroll}>
{children}
</div>
)
}

How do I scroll the page to the top after the fragment identifier pulls the page down?

I am not trying to prevent the fragment identifier from working. I want the page to go back to the top after it goes down.
This question is asked for the purposes of using jQuery's UI tabs. You need the id to be set on the tab content div, so that jQuery knows which tab to open.
The fragment identifier will open the tab that it is set to, but it also scrolls the page down to the tab's content.
On a page with the tab close to the top, and barely any headers, I wish to keep my page at the top, not scroll down ~150 pixels.
Using javascript's onscroll event, we can see when the page scrolls.
Side note - Since I only have one scenario, I verify that my fragment identifier is what it should be.
We need to then keep a count of when the page scrolls. The page should only be set to the top at the beginning, otherwise the user wouldn't be able to scroll. Thus, check the scroll count for 1, and then move the page to the top.
<script type="text/javascript">
var scrollCount = 0;
window.onscroll = function () {
var hash = window.location.hash.substr(1);
if (hash === "chats") {
scrollCount++;
}
if (scrollCount === 1) {
window.scrollTo(0, 0);
}
}
</script>

Categories