AnAspiringCanadian AnAspiringCanadian - 3 years ago 98
React JSX Question

Access class props inside scroll addeventlistener

I am trying to position fix by passing the

fixed
prop from state but I am not able to
setState
inside
handleScroll
function. I am not sure how to access state inside the function.

class App extends Component {

state = { fixed: false }

componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}

componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}

handleScroll(e) {
let scrollTop = e.srcElement.body.scrollTop;
(scrollTop > 0) ? this.setState({ fixed: true }) : this.setState({ fixed: false });
}

render() {
// grab steps
const { steps } = this.props;
const { fixed } = this.state;
const { scrollToStep } = this;

return ce('div', { className:'allTheSteps' },
ce(pagination, { steps, fixed }),
Object.values(steps).map((step, i) =>
ce(Steps, { step, key: v4(), i }),
)
);
};

};

Answer Source

You need to bind the handleScroll method:

class App extends Component {

  constructor(props) {
    super(props);
    this.handleScroll = this.handleScroll.bind(this);
  }

  ...

};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download