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??
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.
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.
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.
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>
)}
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