I have a list which contains a series of items, but I can't get it to scroll another item into view. Solutions such as this doesn't quite work, because I have to scroll up and down (basically if the list is too large, scroll it at intervals to display all items).
I made a codepen that illustrates the problem with react-scroll-to-component, but I am open to any library / native solution. The basic functionality is just scrollToComponent(ref, <options>)
.
The error as far as I can tell is that it attempts to scroll on the body, rather than the actual container. If you remove the height / overflow properties of the div, it will work.
Doesn't work:
<div
style={{
height: `200px`,
overflow: "hidden"
}}
>
{this.state.items.map(item => (
<Item ref={inst => (this[`ref_${item}`] = inst)} item={item} />
))}
</div>
Works:
<div>
{this.state.items.map(item => (
<Item ref={inst => (this[`ref_${item}`] = inst)} item={item} />
))}
</div>
Full code for anyone not wanting to go to codepen:
class Item extends React.Component {
render() {
return <div style={{ padding: `12px` }}>Item {this.props.item}</div>;
}
}
class List extends React.Component {
state = {
items: [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
]
};
componendDidMount() {
this.state.items.forEach(item => (this[`ref_${item}`] = React.createRef()));
}
onClick = () => {
scrollToComponent(this.ref_20);
};
render() {
const { items } = this.state;
return (
<div>
<h1>My List</h1>
<button onClick={this.onClick}>Clickidy</button>
{/*Replace with <div> to see it work*/}
<div
style={{
height: `200px`,
overflow: "hidden",
backgroundColor: "red"
}}
>
{this.state.items.map(item => (
<Item ref={inst => (this[`ref_${item}`] = inst)} item={item} />
))}
</div>
</div>
);
}
}