Home > Enterprise >  How to scroll to a span element inside a div in React, so it is always visible and not overflown
How to scroll to a span element inside a div in React, so it is always visible and not overflown

Time:11-06

There is a div with a bunch of spans inside of it like so:

<div id="wordDisplayWrapper">
  {words.map((word, i) => {
    if (i === idx) {
      return (
        <span key={i} className={"currentWord"}>
          {word}
        </span>
      );
    } else {
      return (
        <span key={i} className={classes[i] || "word"}>
          {word}
        </span>
      );
    }
  })}
</div>;

The spans will overflow off the div, and overflow has been set to overflow-y: hidden;, this is the CSS:

#wordDisplayWrapper {
  height: 5.5em;
  overflow-y: hidden;
  outline: 1px solid orange;
}

The currentWord changes, and as it indexes forward, it overflows the div. I would like the div to scroll to this currentWord automatically, but I have not been able to find a way to do this. How should I go about this in React?

Thanks!

CodePudding user response:

You may target the element to scroll using a a html selector / refs and call scrollIntoView(). Call scrollIntoView(true) if you want the current word to be at the top of the container.

More about Element.scrollIntoView: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

If you want a transition for the scroll, add scroll-behavior: smooth; css rule to the container div.

About scroll-behavior: https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior

  • Related