Blog>
Snippets

Dynamic Margin Adjustment Based on Scroll Position

Showcase a method to dynamically adjust the margin of list items in a virtual scroll setup based on the user's scroll position, enhancing the visual feedback of the current focus item.
class ScrollAwareList extends React.Component {
  constructor(props) {
    super(props);
    this.state = { scrollTop: 0 };
    this.onScroll = this.onScroll.bind(this);
  }

  onScroll({ target: { scrollTop } }) {
    this.setState({ scrollTop });
  }

  renderRow(style, index) {
    // Dynamically adjust margin based on scroll position
    const dynamicMargin = this.state.scrollTop / 10;
    const adjustedStyle = { ...style, marginTop: dynamicMargin };

    return <div style={adjustedStyle}>Item {index}</div>;
  }

  render() {
    return (
      <div onScroll={this.onScroll} style={{ overflow: 'auto', height: '100vh' }}>
        {Array.from({ length: 100 }).map((_, index) =>
          this.renderRow({ height: 30, display: 'flex', alignItems: 'center' }, index)
        )}
      </div>
    );
  }
}
This piece of code defines a React component named ScrollAwareList. It demonstrates how to dynamically adjust the margin of list items based on the user's scroll position within a div. The component tracks the scrollTop value on scroll events and uses this value to calculate a dynamic margin for each list item. The renderRow method is responsible for applying this adjusted margin to simulate focus or emphasis as the user scrolls through the list.