Scroll to y location within react element with useRef - reactjs

I have an component on my page that scrolls, but the rest doesn't. I want to scroll to a certain Y location within this element, when I change a useState value using a different component.
const scrollMe = useRef();
useEffect(
() => {
if (scrollMe === true) {
scrollPanel.scrollTo(0, 300)
}
},
[ scrollMe ]
);
The scrollable component is like so:
<div ref={scrollMe} onScroll={(e) => handleScroll(e)}>A mapped array</div>
The scroll function is as follows:
const handleScroll = (e) => {
if (e.target.scrollTop !== 0) {
setTopBarPosition(true);
} else {
setTopBarPosition(false);
}
};
Setting the topBarPosition affects
<div className={`topBar ${topBarPosition === true ? 'topBarToTop' : ''}`}>
<TopBar/>
</div>
And the css class topBarToTop moves the topBar to the top of the page:
.topBarToTop {
top: 30px;
}
How come I just get scrollMe.scrollTo is not a function ?
I made a codesandbox that illustrates what I'm trying to do:
https://codesandbox.io/s/react-hooks-counter-demo-izho9

You need to make some small changes, Please follow the code comments:
useEffect(() => {
// swap the conditions to check for childRef first
if (childRef && topPosition) {
// use to get the size (width, height) of an element and its position
// (x, y, top, left, right, bottom) relative to the viewport.
const { y } = childRef.current.getBoundingClientRect()
// You have to call `current` from the Ref
// Add the `scrollTo()` second parameter (which is left)
childRef.current.scrollTo(y, 0)
// Initially it was set to `false` and we change it to `true` when click on scroll
// button then we change it back to `false` when re-render
setTopPosition(false)
}
}, [topPosition, childRef])
More about getBoundingClientRect()

Related

Two React useEffect hooks accessing the window onscroll?

I am new to React dev so this may be something simple I am missing with hooks.
Using a template, I have used a header bar which shrinks in height if you scroll down in the page far enough (i.e it is only at max height if you scroll to the top).
I have been customising a sidebar to go along with the headerbar, and I'm trying to get the items within it to also move up when the bottom of the headerbar moves up.
The app bar uses a pre-made function:
import { useState, useEffect } from 'react';
// ----------------------------------------------------------------------
export default function useOffSetTop(top: number) {
const [offsetTop, setOffSetTop] = useState(false);
const isTop = top || 100;
useEffect(() => {
window.onscroll = () => {
if (window.pageYOffset > isTop) {
setOffSetTop(true);
} else {
setOffSetTop(false);
}
};
return () => {
window.onscroll = null;
};
}, [isTop]);
return offsetTop;
}
Then you can just import it, assign a constant bool to useOffSetTop(HEADER.DASHBOARD_DESKTOP_HEIGHT) and base the layout on the state of that const.
In the app bar it controls the height, so in the nav bar I made it control he height of an empty .
It does work, but the app bar stops working.
I do have hot-reload on and if I make a change to the app bar it starts working but the nav bar stops working.
I guess it is just because whichever loads last is the one which binds something to window.onscroll and the other is wiped.
I am just wondering how I could change this function or restructure the code so that this could be imported by multiple components on the same page - possibly without having to just import it higher up and pass the true/false value down through the components?
The issue is that you are actually "overriding" the onScroll function (or replacing it) instead of listening for the event.
by doing this
window.onScroll = null;
you are effectively overriding the onScroll function to do nothing.
Best to listen for the onscroll event.
import { useState, useEffect } from 'react';
export default function useOffSetTop(top: number) {
const [offsetTop, setOffSetTop] = useState(false);
const isTop = top || 100;
const handleOnScroll = () => {
if (window.pageYOffset > isTop) {
setOffSetTop(true);
} else {
setOffSetTop(false);
}
}
useEffect(() => {
window.addEventListener('scroll', handleOnScroll )
return () => {
window.removeEventListener('scroll', handleOnScroll)
};
}, [isTop, handleOnScroll]);
return offsetTop;
}

React Infinite Loading hook, previous trigger

Im trying to make a hook similar to Waypoint.
I simply want to load items and then when the waypoint is out of screen, allow it to load more items if the waypoint is reached.
I can't seem to figure out the logic to have this work properly.
Currently it see the observer state that its on the screen. then it fetches data rapidly.
I think this is because the hook starts at false everytime. Im not sure how to make it true so the data can load. Followed by the opposite when its reached again.
Any ideas.
Here's the hook:
import { useEffect, useState, useRef, RefObject } from 'react';
export default function useOnScreen(ref: RefObject<HTMLElement>) {
const observerRef = useRef<IntersectionObserver | null>(null);
const [isOnScreen, setIsOnScreen] = useState(false);
useEffect(() => {
observerRef.current = new IntersectionObserver(([entry]) => {
if (isOnScreen !== entry.isIntersecting) {
setIsOnScreen(entry.isIntersecting);
}
});
}, []);
useEffect(() => {
observerRef.current.observe(ref.current);
return () => {
observerRef.current.disconnect();
};
}, [ref]);
return isOnScreen;
}
Here's the use of it:
import React, { useRef } from 'react';
import { WithT } from 'i18next';
import useOnScreen from 'utils/useOnScreen';
interface IInboxListProps extends WithT {
messages: any;
fetchData: () => void;
searchTerm: string;
chatID: string | null;
}
const InboxList: React.FC<IInboxListProps> = ({ messages, fetchData, searchTerm, chatID}) => {
const elementRef = useRef(null);
const isOnScreen = useOnScreen(elementRef);
if (isOnScreen) {
fetchData();
}
const renderItem = () => {
return (
<div className='item unread' key={chatID}>
Item
</div>
);
};
const renderMsgList = ({ messages }) => {
return (
<>
{messages.map(() => {
return renderItem();
})}
</>
);
};
let messagesCopy = [...messages];
//filter results
if (searchTerm !== '') {
messagesCopy = messages.filter(msg => msg.user.toLocaleLowerCase().startsWith(searchTerm.toLocaleLowerCase()));
}
return (
<div className='conversations'>
{renderMsgList({ messages: messagesCopy })}
<div className='item' ref={elementRef} style={{ bottom: '10%', position: 'relative',backgroundColor:"blue",width:"5px",height:"5px" }} />
</div>
);
};
export default InboxList;
Let's inspect this piece of code
const [isOnScreen, setIsOnScreen] = useState(false);
useEffect(() => {
observerRef.current = new IntersectionObserver(([entry]) => {
if (isOnScreen !== entry.isIntersecting) {
setIsOnScreen(entry.isIntersecting);
}
});
}, []);
We have the following meanings:
.isIntersecting is TRUE --> The element became visible
.isIntersecting is FALSE --> The element disappeared
and
isOnScreen is TRUE --> The element was at least once visible
isOnScreen is FALSE--> The element was never visible
When using a xor (!==) you specify that it:
Was never visible and just became visible
this happens 1 time just after the first intersection
Was visible once and now disappeared
this happens n times each time the element is out of the screen
What you want to do is to get more items each time the element intersects
export default function useOnScreen(ref: RefObject<HTMLElement>, onIntersect: function) {
const observerRef = useRef<IntersectionObserver | null>(null);
const [isOnScreen, setIsOnScreen] = useState(false);
useEffect(() => {
observerRef.current = new IntersectionObserver(([entry]) => {
setIsOnScreen(entry.isIntersecting);
});
}, []);
useEffect(()=?{
if(isOnScreen){
onIntersect();
}
},[isOnScreen,onIntersect])
...
}
and then use it like:
const refetch= useCallback(()=>{
fetchData();
},[fetchData]);
const isOnScreen = useOnScreen(elementRef, refetch);
or simply:
const isOnScreen = useOnScreen(elementRef, fetchData);
If fetchData changes reference for some reason, you might want to use the following instead:
const refetch= useRef(fetchData);
const isOnScreen = useOnScreen(elementRef, refetch);
Remember that useOnScreen has to call it like onIntersect.current()
In InboxList component, what we are saying by this code
if (isOnScreen) {
fetchData();
}
is that, every time InboxList renders, if waypoint is on screen, then initiate the fetch, regardless of whether previous fetch is still in progress.
Note that InboxList could get re-rendered, possibly multiple times, while the fetch is going on, due to many reasons e.g. parent component re-rendering. Every re-rendering will initiate new fetch as long as waypoint is on screen.
To prevent this, we need to keep track of ongoing fetch, something like typical isLoading state variable. Then initiate new fetch only if isLoading === false && isOnScreen.
Alternatively, if it is guaranteed that every fetch will push the waypoint off screen, then we can initiate the fetch only when waypoint is coming on screen, i.e. isOnScreen is changing to true from false :
useEffect(() => {
if (isOnScreen) {
fetchData();
}
}, [isOnScreen]);
However, this will not function correctly if our assumption, that the waypoint goes out of screen on every fetch, does not hold good. This could happen because
pageSize of fetch small and display area can accommodate more
elements
data received from a fetch is getting filtered out due to
client side filtering e.g. searchTerm.
As my assumption. Also you can try this way.
const observeRef = useRef(null);
const [isOnScreen, setIsOnScreen] = useState(false);
const [prevY, setPrevY] = useState(0);
useEffect(()=>{
fetchData();
var option = {
root : null,
rootmargin : "0px",
threshold : 1.0 };
const observer = new IntersectionObserver(
handleObserver(),
option
);
const handleObserver = (entities, observer) => {
const y = observeRef.current.boundingClientRect.y;
if (prevY > y) {
fetchData();
}
setPrevY(y);
}
},[prevY]);
In this case we not focus chat message. we only focus below the chat<div className="item element. when div element trigger by scroll bar the fetchData() calling again and again..
Explain :
In this case we need to use IntersectionObserver for read the element position. we need to pass two parameter for IntersectionObserver.
-first off all in the hanlderObserver you can see boundingClientRect.y. the boundingClientRect method read the element postion. In this case we need only y axis because use y.
when the scrollbar reach div element, y value changed. and then fetchData() is trigger again.
root : This is the root to use for the intersection. rootMargin : Just like a margin property, which is used to provide the margin value to the root either in pixel or in percent (%) . threshold : The number which is used to trigger the callback once the intersection’s area changes to be greater than or equal to the value we have provided in this example .
finally you can add loading status for loading data.
return (
<div className='conversations'>
{renderMsgList({ messages: messagesCopy })}
<div className='item' ref={observeRef} style={{ bottom: '10%', position: 'relative',backgroundColor:"blue",width:"5px",height:"5px" }} />
</div>
);
};
I hope its correct, i'm not sure. may it's helpful someone. thank you..

Is there anyway to detect the margin of a div?

I want to know the margin-left of div1, so I can use it in my code. Setting it this way, the margin on the left will change depending on the screen size. How can I detect the margin left of this div?
<div class="max-w-6xl m-auto">
</div>
In react, you can make use of the ref callback, which receives the HTML DOM element as an argument. Inside of this callback, you could query the margin-left style from the element and store it in a state. Here's an example:
const App = () => {
const [marginLeft, setMarginLeft] = useState(0); // in pixels
const retrieveMargin = (elm) => {
if (elm != null) {
let styles = window.getComputedStyle(elm);
let ml = styles.getPropertyValue("margin-left");
setMarginLeft(Number.parseInt(ml.replace("px", "")));
}
};
return <div class="mydiv" ref={retrieveMargin}></div>;
};

Trap non interactive element's focus

I have an non interactive element like a div on the page that serves as a loading modal. When it is loading, I want to show this modal as well as the rest of the page containing interactive elements with a opacity of 50%. When it is loading(loading modal shows up), I want the focus trapped in this modal and make it so the user cannot tab through the rest of the elements on the page. I've tried the code below by adding the ReactFocusLock around the div and give the div a tabIndex of -1 so it is focusable and set it to be focusable at the beginning but it does not work. However, if I put a link or something interactable inside the div, it works well, which means the ReactFocusLock is fine. Could you please help?
const MyComponent = () => {
const {loading, data} = fetchData();
return <>
{loading && <LoadingModal />}
{data && <div>data</div>}
<input></input>
<button></button>
<>;
}
// original modal
const LoadingModal = () => {
return <div>loading data....<div>;
}
// modal that with ReactFocusLock from react-focus-lock
const LoadingModal = () => {
const ref = React.useRef(null);
React.useEffect(() => {
ref.current.focus();
}, []);
return <ReactFocusLock><div ref={ref} tabIndex={-1}>loading data....</div></ReactFocusLock>;
}

React SSR, Proper way of handling page scroll position

My goal is to apply different className depending on the user's scroll position. Well, I need to change the background color of the navbar if the user's scroll position is > 0. I came up with a working solution that works in all cases except the one if the user loads a page and initial scroll position is not 0 (scrolled and then reloaded the page).
What I did is I created a custom hook which looks like this:
import { useState, useEffect } from 'react';
export default () => {
const [scrollPosition, setScrollPosition] = useState(
typeof window !== 'undefined' ? window.scrollY : 0,
);
useEffect(() => {
const setScollPositionCallback = () => setScrollPosition(window.scrollY);
if (typeof window !== 'undefined') {
window.addEventListener('scroll', setScollPositionCallback);
}
return () => {
if (typeof window !== 'undefined') {
window.removeEventListener('scroll', setScollPositionCallback);
}
};
}, []);
return scrollPosition;
};
And then I use this hook in my Navbar component:
...
const scrollPosition = useScrollPosition();
...
<Navbar
color={scrollPosition < 1 ? 'transparent' : 'white'}
...
/>
As I described, everything works well if the user loads the page at the 0 scrollY. When it's not, I get the warning Warning: Prop className did not match, which is expected, because scrollY is always 0 on the server side and then scrolling doesn't work, because Navbar keeps ssr class.
What is the proper way of handling it?
I've found a solution. The reason why it was happening is, due to this line in the hook:
const [scrollPosition, setScrollPosition] = useState(
typeof window !== 'undefined' ? window.scrollY : 0,
);
scroll position was equal to 0 all the time on ssr, but when loaded on the client side, it was set to actual scrollY at the beginning.
So what I did is I set initial scrollPosition to 0 on both client and server side by modifying the line below to:
const [scrollPosition, setScrollPosition] = useState(0);
and the added one more effect that works on client side only, which sets scrollPosition:
useEffect(() => {
if (typeof window !== 'undefined' && window.scrollY !== 0) {
setScrollPosition(window.scrollY);
}
}, []);

Resources