Home >Web Front-end >JS Tutorial >How to Scroll Automatically to a Specific Element in React?

How to Scroll Automatically to a Specific Element in React?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 10:51:12339browse

How to Scroll Automatically to a Specific Element in React?

How to Scroll Automatically to a Specific Element?

Problem:

In a chat widget, new messages should automatically scroll into view as the user scrolls up. However, the slider remains fixed at the top when new messages load, making it difficult to see the latest ones.

Solution:

To scroll to a specific element when new messages are added, follow these steps:

React 16.8 , Functional component

const ScrollDemo = () => {
  const myRef = useRef(null);
  const executeScroll = () => myRef.current.scrollIntoView(); // Run this function to execute scroll
  return (
    <>
      <div ref={myRef}>Element to scroll to</div>
      <button onClick={executeScroll}>Click to scroll</button>
    </>
  );
};

React 16.3 , Class component

class ReadyToScroll extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  render() {
    return <div ref={this.myRef}>Element to scroll to</div>;
  }

  executeScroll = () => this.myRef.current.scrollIntoView(); // Run this method to execute scrolling
}

Class component - Ref callback

class ReadyToScroll extends Component {
  render() {
    return (
      <div ref={(ref) => (this.myRef = ref)}>Element to scroll to</div>
    );
  }

  executeScroll = () => this.myRef.scrollIntoView(); // Run this method to execute scrolling
}

Avoid String Refs:

String refs are discouraged due to performance issues, lack of composability, and potential removal in future React releases.

Optional: Smooth Scroll Animation:

For a smooth scrolling experience, add the following CSS to the html element:

html {
  scroll-behavior: smooth;
}

Passing Ref to a Child:

To attach a ref to a specific DOM element within a child component:

const MyComponent = () => {
  const myRef = useRef(null);
  return <ChildComp refProp={myRef} />;
};

Within the ChildComp component:

const ChildComp = (props) => {
  return <div ref={props.refProp} />;
};

The above is the detailed content of How to Scroll Automatically to a Specific Element in React?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn