Lara
Lara

Reputation: 3021

How to add scroll into listItem of list on search

I have a List which contains ListItem and a search bar. Search functionality is working well as per the requirement and its highlighting the ListItem. Now i am trying to add the scroll so that the List gets scroll to first occurrence of the 'includes' if the search item is not available on visible window but not able to implement it. Tried const ref = React.createRef();

How to get it working?

Here is the codesandbox link

Upvotes: 1

Views: 53

Answers (1)

johannchopin
johannchopin

Reputation: 14873

You can easily achieve this one using vanilla js.

First just store the index of all matching ListItem in a state:

  const getMatchingListItems = React.useCallback(() => {
    return [...messages]
      .map(({ id, primary, secondary, person }, i) => {
        if (secondary.includes(searchTranscript) && searchTranscript !== "") {
          return i;
        }
      })
      .filter((elmt) => elmt !== undefined);
  }, [searchTranscript]);

  const [matchingListItems, setMatchingListItems] = useState(getMatchingListItems());

Use it to define which className to use:

<div
  className={
    matchingListItems.includes(i) ? classes.searchHighLight : ""
  }

And finally use the useEffect hook to scroll to the first matching LisItem when matchingListItems is updated:

   React.useEffect(() => {
    setMatchingListItems(getMatchingListItems());
  }, [getMatchingListItems, setMatchingListItems]);

  React.useEffect(() => {
    const firstListMatch = matchingListItems[0];

    if (firstListMatch) {
      const firstLi = document.querySelector(
        `ul div:nth-child(${firstListMatch})`
      );
      firstLi.scrollIntoView();
    } else {
      document.querySelector("ul").scrollIntoView();
    }
  }, [matchingListItems]);

You can try it using this codesandbox.

Upvotes: 1

Related Questions