最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React: [useRef, scrollIntoView,] How to only autoscroll a specific div inside of an overflowing page? - Stack Overf

programmeradmin2浏览0评论

As you can see in my example

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

function App() {
  const items = ["this", "that", "those", "them", "these", "thisins"];

  const messagesRef = React.useRef(null);
  const scrollToBottom = () => {
    messagesRef.current.scrollIntoView({
      behavior: "smooth"
    });
  };

  React.useEffect(() => {
    if (messagesRef.current) {
      scrollToBottom();
    }
  }, [messagesRef]);

  return (
    // Page is overflowing, set height to mimic a full page
    <div className="App" style={{ marginTop: 70, height: 800 }}>
      {/* now set this div to overflow scroll with a small height */}
      <div style={{ overflowY: "scroll", height: 200, border: "solid" }}>
        {items.map(elem => (
          <div style={{ border: "solid", borderColor: "green", padding: 20 }}>
            {elem}
          </div>
        ))}
        {/* Set last element within this div to be the ref to scroll to */}
        <div ref={messagesRef} />
      </div>
    </div>
  );
}
<script src=".12.0/umd/react.production.min.js"></script>
<script src=".12.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>

As you can see in my example

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

function App() {
  const items = ["this", "that", "those", "them", "these", "thisins"];

  const messagesRef = React.useRef(null);
  const scrollToBottom = () => {
    messagesRef.current.scrollIntoView({
      behavior: "smooth"
    });
  };

  React.useEffect(() => {
    if (messagesRef.current) {
      scrollToBottom();
    }
  }, [messagesRef]);

  return (
    // Page is overflowing, set height to mimic a full page
    <div className="App" style={{ marginTop: 70, height: 800 }}>
      {/* now set this div to overflow scroll with a small height */}
      <div style={{ overflowY: "scroll", height: 200, border: "solid" }}>
        {items.map(elem => (
          <div style={{ border: "solid", borderColor: "green", padding: 20 }}>
            {elem}
          </div>
        ))}
        {/* Set last element within this div to be the ref to scroll to */}
        <div ref={messagesRef} />
      </div>
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

<div id="root"></div>

The page loads, and both the page and the nested scrolling div auto scroll.

What I'm trying to do is only scrollIntoView the overflowing div I have set as my ref.

I'm targetting the ref, and it is working, but how do I NOT scroll the parent element as well?

Share Improve this question edited Feb 18, 2020 at 21:42 Patrick Roberts 51.9k10 gold badges117 silver badges162 bronze badges asked Feb 18, 2020 at 21:21 bauervisionbauervision 8872 gold badges9 silver badges25 bronze badges 3
  • Interestingly enough your code causes the parent frame to scroll as well... – Patrick Roberts Commented Feb 18, 2020 at 21:44
  • right, that is the essence of what I'm trying to subvert – bauervision Commented Feb 19, 2020 at 1:02
  • scrollToBottom should also be added as a dependency of the useEffect hook. – coler-j Commented Jan 14, 2021 at 18:04
Add a comment  | 

3 Answers 3

Reset to default 15

Try this:

   messagesRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "start"
    });

I was having an issue with it scrolling to the top with the above configuration. I just added the behavior: "smooth" option and it works perfectly :)

Create the ref to the element:

const recogRef = useRef();

I have this in a switch statement inside the userActions method that checks the onClick event:

case "recognition":
  recogRef.current.scrollIntoView({
    behavior: "smooth",
  });
  break

Then add the ref to an element you want to scroll to:

<h3 ref={recogRef} className="m-0">
  Recognitions for {`${participant.firstName}`}
</h3>

Note, this was in an Object.keys(obj).map methon
And then the element that triggers the action call:

<div
  key={key}
  onClick={() => userActions(key)}
  className="user_action d-flex align-items-center justify-content-center"
>
  <p className="mb-0 ms-1 fw-bold">{actions[key].label<}/p>
</div>

i tried this use case in react and work for horizontal scroll

    useEffect(() => {
     const element = document.getElementById(selectedDay);
     if (element) {
      element.scrollIntoView({
      behavior: "smooth",
      block: "end",
      inline: "nearest"
     });
     }
     }, [selectedDay]);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论