Search code examples
javascriptreactjsscrollautoscroll

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

Solution

  • 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/