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

81
November 05, 2021, at 10:40 PM

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!

Answer 1

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

READ ALSO
My Tflite model works perfectly in jupyter notebook. However shows me the wrong output when I try to run it in Android studio

My Tflite model works perfectly in jupyter notebook. However shows me the wrong output when I try to run it in Android studio

So I created my custom model for disease recognition based on the symptoms entered by the patientAnd it works perfectly on python, However after I converted it to tflite and ran it on android studio, It gives me wrong predictions irrespective of the input values

99
MySQL Header exclusion

MySQL Header exclusion

I'm trying to return all columns from a group of tables I'm joiningWe have some replacement data in columns to not publicly disclose certain information, each of those columns contains a very specific string after the columns original name

85
CSS Position For Div

CSS Position For Div

I have 2 main divs, one will be displayed while the other is hiddenWhen the hidden div appears, the previous one disappears

96