Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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??

like image 759
Shatha Avatar asked Dec 13 '18 07:12

Shatha


People also ask

How do you load search results when scrolling down the page in react JS?

import React, { useState } from "react"; import axios from "axios"; import './App. css'; import 'bootstrap/dist/css/bootstrap. min. css'; const App = () => { const [searchTerm, setSearchTerm] = useState(""); const [books, setBooks] = useState({ items: [] }); const onInputChange = e => { setSearchTerm(e.

How do you scroll down to a particular element in react?

To scroll to an element on click in React:Set a ref prop on the element you want to scroll to. Set the onClick prop on the other element. Every time the element is clicked, call the scrollIntoView() method on the ref object.

How do you scroll to the bottom of the page using react?

To scroll to the bottom of a div in React: Add an element at the bottom of the div . Set a ref on the element at the bottom. When an event occurs, call the scrollIntoView() method on the ref object.


1 Answers

I have tried many libraries but couldn't find something that best suited my needs so i wrote a custom hook for that, I hope it helps

import { useState, useEffect } from "react";

const OPTIONS = {
  root: null,
  rootMargin: "0px 0px 0px 0px",
  threshold: 0,
};

const useIsVisible = (elementRef) => {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    if (elementRef.current) {
      const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setIsVisible(true);
            observer.unobserve(elementRef.current);
          }
        });
      }, OPTIONS);
      observer.observe(elementRef.current);
    }
  }, [elementRef]);

  return isVisible;
};

export default useIsVisible;

and then you can use the hook as follows :

import React, { useRef } from "react";
import useVisible from "../../hooks/useIsVisible";

function Deals() {
  const elemRef = useRef();
  const isVisible = useVisible(elemRef);
  return (
    <div ref={elemRef}>hello {isVisible && console.log("visible")}</div>
)}
like image 89
inzo Avatar answered Sep 19 '22 14:09

inzo