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


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!


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:

<div id="cswscrollable" className="scrollable-y maxh-001">
	..code to render checkboxes here

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

constructor(props) {
	this.state = {
		ctwScrollTop:0 //category tree wrapper scroll top position

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

onCheckedCategory = () =>	{
	var el = document.getElementById('cswscrollable'); //wrapper div any other actions which do not change state of anything. If you need to set state multiple times set the ctwScrollTop at the top of this function.
	//now set states
	this.setState({ctwScrollTop: el.scrollTop, anyotherstates:and its values...}, this.afterCheckedCategory);
afterCheckedCategory = () =>	{
	//get the ctwScrollTop value and set the scrollTop property after everything has finished rendering
	var el = document.getElementById('cswscrollable');
	el.scrollTop = this.state.ctwScrollTop;

Leave a Reply