简体   繁体   中英

How to get exact DOM element using useRef in React

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM