0

I have a React app in which I render a horizontal list draft picks. At any point in time, one draft pick is active, but at a certain point that pick is made, and then the next one becomes active. When the next one becomes active, I'd like for the list to auto-scroll horizontally so that the active pick is always in view.

I'm sure this has been asked before, but I don't really know how to cause an auto-scroll event to a React component.

Here's the code I have:

DraftOrder.js:

class DraftOrder extends React.Component {
  render() {
    return (
      <React.Fragment>
        <div className="d-flex flex-row auto-scroll-x">
          {this.props.draftPicks.map(aDraftPick => {
            return <ADraftPickInOrder key={v4()} draftPick={aDraftPick} team={this.props.team} />
          })}
        </div>
      </React.Fragment>
    );
  }
}

ADraftPickInOrder.js:

class ADraftPickInOrder extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      active: this.props.draftPick.active
    }
    this.renderUserName = this.renderUserName.bind(this);
    this.renderDraftedPlayer = this.renderDraftedPlayer.bind(this);
  }


  renderUserName() {
     ...
  }

  renderDraftedPlayer() {
    ...
  }

  render() {
    return (
      <div className="text-center px-3">
        <div className={classnames("font-weight-bold no-wrap", { "text-success" : this.props.draftPick.team.id === this.props.team.id } )}>{this.props.draftPick.team.name}</div>
        {this.renderUserName()}
        {this.renderDraftedPlayer()}
        <div><small>{formatDraftPickNumber(this.props.draftPick)}</small></div>
      </div>
    );
  }
}

Any help would be much appreciated!

Nathan Lauer
  • 381
  • 5
  • 18

1 Answers1

0

Use ScrollView and the scrollTo method of it:

import { ScrollView } from 'react-native';

...

setScrollViewRef = ref => {
  this.scrollView = ref;
};

handlePress = ({nativeEvent}) => {
  const { pageX, pageY } = nativeEvent;
  // find out x and y somehow
  this.scrollView.scrollTo({x, y, animated: true})
}


render() {
  <ScrollView
    horizontal 
    ref={this.setScrollViewRef}
    showsHorizontalScrollIndicator={false}>
     <DraftPick onPress={this.handlePress} />
     <DraftPick onPress={this.handlePress} />
     ...
  </ScrollView>
}
gazdagergo
  • 6,187
  • 1
  • 31
  • 45
  • 2
    Is there an equivalent way to achieve this in a React web app, not React Native? – Nathan Lauer Aug 17 '18 at 13:39
  • Oh, sorry, I gave you a native example in deed. What about this post? It might give some hints: https://stackoverflow.com/questions/30495062/how-can-i-scroll-a-div-to-be-visible-in-reactjs – gazdagergo Aug 18 '18 at 18:11