I followed the instruction from this post Update style of a component onScroll in React.js to register event listener for scroll event.
I have a React component that renders a Table component from the React-Bootstrap library https://react-bootstrap.github.io/
I think I registered the event listener correctly but I am not sure why when I scroll down the table, my handleScroll() callback is not getting invoked. Is it because the event listener is not registered on the actual table itself?
Thanks for taking your time reading my question. Any feedback is appreciated.
Here's a snippet of how I register for the event listener.
handleScroll: function(event) {
console.log('handleScroll invoked');
},
componentDidMount: function() {
console.log('componentDidMount invoked');
window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount: function() {
console.log('componentWillUnmount invoked');
window.removeEventListener('scroll', this.handleScroll);
},
Here's a snippet of my render function.
render: function() {
var tableRows = this.renderTableRow(this.props.sheet);
return (
<Table striped bordered condensed hover>
<TableHeaderContainer
tableTemplateName={this.props.tableTemplateName}
sheetName={this.props.sheet.name}/>
<tbody>
{tableRows}
</tbody>
</Table>
);
}
To add scroll event listeners in a React component, we can set the onScroll prop of an element to an event handler function. We create the onScroll function that logs the scroll event object. Then we assign the onScroll function as the value of the onScroll prop of the div.
To handle the onScroll event in React: Set the onScroll prop on an element or add an event listener on the window object. Provide an event handler function. Access relevant properties on the event or window objects.
Your code looks good, so it's probably not the window itself that is scrolling. Is the table placed inside a div
or something that has overflow: auto
or overflow:scroll
? If so, the listener must be attached to the actual element that is scrolling, e.g.
document.querySelector('.table-wrapper')
.addEventListener('scroll', this.handleScroll);
If this is the case, then just adding a React onScroll handler to the wrapper in your code would be better
<div onScroll={this.handleScroll}><Table....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With