Creating a scroll position indicator in React

I am trying to encode a scroll progress indicator in React. I work with jQuery, but would like to know how to do this with pure Javascript.

componentDidMount() { window.addEventListener('scroll', this.handleScroll); } handleScroll() { var winHeight = $(window).height(), docHeight = $(document).height(), value = $(window).scrollTop(), max, percent; max = docHeight - winHeight; percent = (value / max) * 100; this.props.updatePercent(percent); } 

Also, should I do this in pure Javascript? I was told that jQuery should not be used in React.

+5
source share
2 answers

Is this the only place you used jQuery? If so, I would recommend using it for pure javascript. Everything you can do with jQuery, you can also use with React and pure JavaScript, and there is no overhead.

Here is your version of handleScroll . Note that the height of the document is known to be annoying when calculating, but I used the approach of this question (which just reproduces the jQuery implementation).

 handleScroll() { var winHeight = window.innerHeight; // Annoying to compute doc height due to browser inconsistency var body = document.body; var html = document.documentElement; var docHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); var value = document.body.scrollTop; ... } 

Update

If you want to get the scroll position inside an element, you will need something like

 var el = document.getElementById('story_body'); var minPixel = el.offsetTop; var maxPixel = minPixel + el.scrollHeight; var value = document.body.scrollTop; // respect bounds of element var percent = (value - minPixel)/(maxPixel - minPixel); percent = Math.min(1,Math.max(percent, 0))*100; 
+12
source

To answer the second question: in this particular case, you can just stick with jQuery (although I prefer the javascript version for vanilla).

With responsiveness, itโ€™s great to use jQuery for:

  • information about reading from a real DOM that is not known to respond (for example, the height of a component in the DOM or the scroll position in your case)
  • ajax stuff

With React, you should NOT use jQuery to:

  • Manipulating the DOM directly: Only manipulate the DOM through reaction. (manipulating the DOM with jQuery in the reaction is a guarantee of big trouble)
  • Reading DOM information that can and should be known in order to respond, for example, the value of an input field. (things really don't break, but it makes your response code harder to debug if you use jQuery to bypass strict development guidelines)
+5
source

Source: https://habr.com/ru/post/1247980/


All Articles