ReactJS check radio/checkbox buttons and scrolling of wrapper div to top – fixed

Issue:

There is a long list of categories to select from. Since the list was long and it could not fit within the wrapper div the maximum height of the wrapper div had to be set and make the wrapper div scrollable by using css properties. Here comes the issue. Whenever a category is checked the react state is changed which caused the component to re-render the html. The re-rendering of html cause to show the upper part visible and not the area which was in the view port while checking the category. Makes sense? Read on!

Solution:

To use scrollTop property of the wrapper div. When checkbox is checked or unchecked the scroll position of the element is to be saved and when it rendered the wrapper div after state changes to use the previously saved srollTop value to set the new scrollTop property of the element which makes the element to scroll to the position where you checked or unchecked the checkbox. See figures below:

Before Checking the button
After checking the button

Example code:

Suppose the wrapper div html in render function of component is:



		


Set a state variable to initialize the position of the wrapper div



		


The code set the scroll position before and after the re-rendering of the component



		




		


Leave a Reply

Your email address will not be published. Required fields are marked *