I have a long list component that consists of some big elements. These elements can trigger a notification in a sidebar. I have a sidebar in which I want to be able to scroll to a particular notification: one that triggered this notification. Hence the question from the title:
Can I store some long list of refs within a context? To then use that list to access a ref of a particular element from my list and simply call .scrollIntoView(). I’ve tried:
I created a context like this:
import { createContext, createRef, useContext } from "react";
const ElementRefsContext = createContext();
const elementRefs = createRef({});
export const ElementRefsProvider = ({ children }) => {
return (
<ElementRefsContext.Provider value={elementRefs}>
{children}
</ElementRefsContext.Provider>
);
};
export const useElementRefsContext = () => {
return useContext(ElementRefsContext);
};
function LongListOfBigElements() {
const { elementRefs } = useElementRefsContext();
return (
<>
{messages?.map((message, index) => (
<BigElement
ref={(el) => {
const messageId = message.message_id;
const elementId = index;
if (elementRefs) {
console.log(workDropdownRefs);
if (!elementRefs.current[messageId]) {
elementRefs.current[messageId] = {};
}
elementRefs.current[messageId][
elementId
] = el;
}
}}/>)
</>