Reputation: 3021
I am trying to get the exact DOM element in the ListItem of List using 'React.useRef(null);' but not able to get it, i am using below code
useEffect(() => {
//This is where i am trying to get the exact DOM element
console.log("listRef", listRef.current);
}, [searchText]);
Here is my codesandbox link
How to get exact DOM element and what am i missing?
Upvotes: 0
Views: 2697
Reputation: 4278
Change your useRef to
const listRef = useMemo(() => messages.map(() => React.createRef<HTMLElement>()), [])
For each list item, set
ref={listRef[id]}
Call the respective item to scroll to using
listRef && listRef[id] && listRef[id].current.scrollIntoView({behavior: "smooth", block: "nearest"});
https://codesandbox.io/s/material-message-search-0x04c?file=/demo.tsx
Upvotes: 2
Reputation: 3345
Here you go with the code :
Declare the refs array :
const listRef = React.useMemo(() => messages.map(() => React.createRef()), []);
Update your useEffect code as below:
useEffect(() => {
//This is where i am trying to get the exact DOM element
let index = 1;
for (let i = 0; i < messages.length; i++) {
if (
messages[i].primary.includes(searchText) ||
messages[i].secondary.includes(searchText)
) {
index = i;
break;
}
}
listRef[index+1].current.scrollIntoView({
behavior: "smooth",
block: "nearest"
});
}, [searchText]);
Working code example: https://codesandbox.io/s/material-demo-forked-bm4pl?file=/demo.tsx
Upvotes: 1