Reputation: 395
I am trying to create a panel where a list of item is presented, once an item is clicked, the right hand side should display the item selected. The left hand side should contain a list of items. The list of items can be very long therefore, i have limited the max height of the list such that when it exceeds this height, it will create a scroll bar so user can scroll down to see the rest of the list. The problem is, whenever an item at the bottom of the list is clicked, the list automatically scrolls back up to the top. I have a feeling that this is due to the fact that I am using a state to pass the item around, and when the item is changed, it causes a re-render thus "reseting" the list. Can someone give me a suggestion as to how i can stop this from happening? Any pointers would be greatly appreciated!
Here is the sandbox: https://codesandbox.io/s/sad-archimedes-3u4k0?file=/src/App.js
ex/ scroll to the bottom and click "random30" and the list goes back up to "random1"
Upvotes: 1
Views: 4148
Reputation: 4536
This happens because you placed a component EventListContainer
inside of EventsList
component which will lead to "re-render" every time you update the state.
You can just move ScrollContainer
directly inside the EventsList
component return
:
return (
<ListContainer>
<ScrollContainer>
{eventListSorted.map(event => {
return (
<EventContainer
onClick={e => {
onSelect(event);
setSelectedEvent(event);
}}
selected={selectedEvent ? selectedEvent.id === event.id : false}
>
{event.uiString}
</EventContainer>
);
})}
</ScrollContainer>
</ListContainer>
);
Also you better move the eventListSorted
array outside the EventsList
component.
sandbox example.
Upvotes: 3