deepseas
deepseas

Reputation: 133

Using eventlistener in reactjs(JSX)

I am trying to learn Reactjs but I am not able to work it out. I want to add sticky header class to my table which is rendered using Reactjs but I am not getting any success with this code/pseudocode.

handleScroll: function(e){
  var header = this.root.querySelector('.header');
var origOffsetY = header.offsetTop;
  window.scrollY >= origOffsetY ? header.addClass('sticky'): header.removeClass('sticky');
},

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

I am trying to use this Javascript function:

<script>
var header = document.querySelector('.header');
var origOffsetY = header.offsetTop;

function onScroll(e) {
  window.scrollY >= origOffsetY ? header.classList.add('sticky') :
                                  header.classList.remove('sticky');
}

document.addEventListener('scroll', onScroll);
</script>

But I am not getting any success. Is there any easier way to implement javascript function in Reactjs?

Upvotes: 0

Views: 3350

Answers (1)

Sophie Alpert
Sophie Alpert

Reputation: 143114

In the line

window.addEventListener('handleScroll', this.handleScroll);

I'm guessing you meant instead:

window.addEventListener('scroll', this.handleScroll);

Upvotes: 3

Related Questions