ReactJS how to render a component only when scroll down and reach it on the page?

Shatha picture Shatha · Dec 13, 2018 · Viewed 10.4k times · Source

I have a react component Data which includes several charts components; BarChart LineChart ...etc.

When Data component starts rendering, it takes a while till receiving the data required for each chart from APIs, then it starts to respond and render all the charts components.

What I need is, to start rendering each chart only when I scroll down and reach it on the page.

Is there any way could help me achieving this??

Answer

Dima Vishnyakov picture Dima Vishnyakov · Dec 13, 2018

You have at least three options how to do that:

  1. Track if component is in viewport (visible to user). And then render it. You can use this HOC https://github.com/roderickhsiao/react-in-viewport

  2. Track ‘y’ scroll position explicitly with https://react-fns.netlify.com/docs/en/api.html#scroll

  3. Write your own HOC using Intersection Observer API https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

To render component you may need another HOC, which will return Chart component or ‘null’ based on props it receives.