is it possible to get scroll position in material-ui
list on Scroll, if so, how?
I am trying to add infinite scroll on the select list since I have 5300 elements and it takes forever to render all those elements.
Yes you can. You need to add a scroll handler and test the scrollTop
of the list vs the scrollHeight
. Please add some code to your questions next time this way it will be easier for people to help you.
function LongList(props) {
function loadMoreItems(event) {
if (event.target.scrollTop === event.target.scrollHeight) {
//user is at the end of the list so load more items
}
}
return (
<List
onScroll={loadMoreItems}
style={{
maxHeight:300,
overflowY:'scroll'
}}
>
<ListItem></ListItem>
<ListItem></ListItem>
<ListItem></ListItem>
<ListItem></ListItem>
</List>
)
}
Edit: to target the list of a <Select>
you need to target the <Menu>
component composing the list of the select using the MenuProps
prop.
<Select
MenuProps={{
PaperProps: {
onScroll:loadMoreItems
}
}}
>
{...menuItems}
</Select>
The way to target inner components in material-ui
is described in their api approach documentation.
Notice there response correct is use MenuProps, with Mayus:
<Select
MenuProps={{
onScroll:loadMoreItems
}}
>
{...menuItems}
</Select>
pay attention the height value plus event.target.scrollTop equals event.target.scrollHeight.
const HeightPanel=300;
function LongList(props) {
function loadMoreItems(event) {
if (event.target.scrollTop+HeightPanel === event.target.scrollHeight) {
//user is at the end of the list so load more items
}
}
return (
<List
onScroll={loadMoreItems}
style={{
maxHeight:HeightPanel,
overflowY:'scroll'
}}
>
<ListItem></ListItem>
<ListItem></ListItem>
<ListItem></ListItem>
<ListItem></ListItem>
</List>
)
}
answer from Anwardo
For a select list you can do it like this:
const loadMoreItems = (e) => {
const bottom = e.target.scrollHeight === e.target.scrollTop + e.target.clientHeight;
if(bottom){
// add your code here
}
};
<Select
labelId="selectList"
id="list"
value={value}
onChange={handleChange}
MenuProps={{
PaperProps: {
onScroll: loadMoreItems,
},
style: {
maxHeight: 500,
},
}}
input={<Input />}
>
<MenuItem></MenuItem>
<MenuItem></MenuItem>
</Select>