Scroll an element into view using React JS Refs
It is common in applications to have a scrollable list of elements. Depending on the interactions, the element should be automatically scrolled into the visible area of the browser window. On adding such scrolling behaviour, it enhances the user experience of the application by avoiding manual dragging and finding the specific element.
To implement scrolling to a particular section based on the chosen element, here are the steps to follow:
1. Adding ref attribute.
Here, ref attribute is set to a callback function. The function gets called twice during updates, first with null and then again with DOM element.ie. on component mount it is called with the DOM node and while component unmount it is called with null.
2. Setting scroll position.
Now in our componentDidMount function, need to set the scrollTop property. The clientHeight,which returns inner height of an element and is set to the scrollTop property. Thus it scroll the contents of a component to an approximate of clientHeight pixels vertically.
To implement scrolling to a particular section based on the chosen element, here are the steps to follow:
1. Adding ref attribute.
Here, ref attribute is set to a callback function. The function gets called twice during updates, first with null and then again with DOM element.ie. on component mount it is called with the DOM node and while component unmount it is called with null.
2. Setting scroll position.
Now in our componentDidMount function, need to set the scrollTop property. The clientHeight,which returns inner height of an element and is set to the scrollTop property. Thus it scroll the contents of a component to an approximate of clientHeight pixels vertically.
Comments
Post a Comment