In this code
useEffect(() => {
divRef?.current?.scrollIntoView({ behavior: 'instant', block: 'nearest' });
}, [currentChat]);
<Stack
key={index}
className={`${msg?.senderId === user?._id
? "message self align-self-end flex-grow-0"
: "message align-self-start flex-grow-0"}`
}
>
<span>{msg.text}</span>
<span className="message-footer">
{moment(msg.createdAt).format("LLL")}
</span>
** <div re`f={divRef}></div>**
</Stack>
In useEffect
when I have currentChat
as a dependency and when it changes it triggers the useEffect
callback but it doesn’t render the UI and when I remove the dependency and run like this
useEffect(() => {
divRef?.current?.scrollIntoView({ behavior: 'instant', block: 'nearest' });
});
Then it renders the UI. Why so? I understand without dependencies it renders every time but why with dependency it triggers useEffect
callback but doesn’t change the scroll position?
I have tried useState
and useLayoutEffect
but both of them didn’t work.
Rishab Mehta is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
This approach working for me, Hope it will work for you,
define the divRef with useRef
const divRef = useRef(null);
useEffect(() => {
divRef.current?.scrollIntoView({ behavior: ‘instant’, block: ‘nearest’ }); }, [currentChat]);
<Stack key={index} className={`${msg.senderId === user._id
? "message self align-self-end flex-grow-0"
: "message align-self-start flex-grow-0"}`
}
>
<span>{msg.text}</span>
<span className="message-footer">
{moment(msg.createdAt).format("LLL")}
</span>
{/* Assign `divRef` to the last element */}
{index === messages.length - 1 && <div ref={divRef}></div>}
</Stack>
Akshay Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.