简体   繁体   中英

React Auto Scroll to show Fetched Data

Im new to react and im trying to auto scroll to Section where data will be shown after being fetched

scrolling should be after data is fetched

const  App = () => {
const [Data ,setData] = useState([])
const [InputTracking , setInputTracking] = useState('')
const [isLoading,setIsLoading] = useState(false)
const [Clicked , setClicked] = useState(false)
//button onClick function 
const searchTrackingID = async (TrackingID) => {
     console.log(TrackingID)
      setIsLoading(true);
      const response = await axios(API_URL+TrackingID) ;
      const res = await response.data ; 
      setData(res)
      setIsLoading(false);
      setClicked(true);
  }
}
 return (
<Header />
//here a form with a text input and button (after clicking it , wait for Data to change state then AUTO SCROLL TO Data (section)
 <section >
  <div >
    <div >
{
   Data.slice(1).reverse().map((mydata)=>(
   <TrackingInfo  Maindata={mydata}/>
   ))
} 
  </div>
  </div>
</section> 
) 
function TestComponent() {
   const testRef = useRef(null);
   const scrollToElement = () => testRef.current.scrollIntoView();
  useEffect(()=>{
  if(loading){
    scrollToElement()
  }
  }, [loading])
 

  // Once the scrollToElement function is run, the scroll will show the element
  return (
    <>
      <div ref={testRef}>Element you want to view</div>
    </>
  );
}

Reference : https://www.delftstack.com/howto/react/scroll-to-an-element-in-react/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM