How can I scroll a div to be visible in ReactJS?
Solution 1
I assume that you have some sort of List
component and some sort of Item
component. The way I did it in one project was to let the item know if it was active or not; the item would ask the list to scroll it into view if necessary. Consider the following pseudocode:
class List extends React.Component {
render() {
return <div>{this.props.items.map(this.renderItem)}</div>;
}
renderItem(item) {
return <Item key={item.id} item={item}
active={item.id === this.props.activeId}
scrollIntoView={this.scrollElementIntoViewIfNeeded} />
}
scrollElementIntoViewIfNeeded(domNode) {
var containerDomNode = React.findDOMNode(this);
// Determine if `domNode` fully fits inside `containerDomNode`.
// If not, set the container's scrollTop appropriately.
}
}
class Item extends React.Component {
render() {
return <div>something...</div>;
}
componentDidMount() {
this.ensureVisible();
}
componentDidUpdate() {
this.ensureVisible();
}
ensureVisible() {
if (this.props.active) {
this.props.scrollIntoView(React.findDOMNode(this));
}
}
}
A better solution is probably to make the list responsible for scrolling the item into view (without the item being aware that it's even in a list). To do so, you could add a ref
attribute to a certain item and find it with that:
class List extends React.Component {
render() {
return <div>{this.props.items.map(this.renderItem)}</div>;
}
renderItem(item) {
var active = item.id === this.props.activeId;
var props = {
key: item.id,
item: item,
active: active
};
if (active) {
props.ref = "activeItem";
}
return <Item {...props} />
}
componentDidUpdate(prevProps) {
// only scroll into view if the active item changed last render
if (this.props.activeId !== prevProps.activeId) {
this.ensureActiveItemVisible();
}
}
ensureActiveItemVisible() {
var itemComponent = this.refs.activeItem;
if (itemComponent) {
var domNode = React.findDOMNode(itemComponent);
this.scrollElementIntoViewIfNeeded(domNode);
}
}
scrollElementIntoViewIfNeeded(domNode) {
var containerDomNode = React.findDOMNode(this);
// Determine if `domNode` fully fits inside `containerDomNode`.
// If not, set the container's scrollTop appropriately.
}
}
If you don't want to do the math to determine if the item is visible inside the list node, you could use the DOM method scrollIntoView()
or the Webkit-specific scrollIntoViewIfNeeded
, which has a polyfill available so you can use it in non-Webkit browsers.
Solution 2
For React 16, the correct answer is different from earlier answers:
class Something extends Component {
constructor(props) {
super(props);
this.boxRef = React.createRef();
}
render() {
return (
<div ref={this.boxRef} />
);
}
}
Then to scroll, just add (after constructor):
componentDidMount() {
if (this.props.active) { // whatever your test might be
this.boxRef.current.scrollIntoView();
}
}
Note: You must use '.current,' and you can send options to scrollIntoView:
scrollIntoView({
behavior: 'smooth',
block: 'center',
inline: 'center',
});
(Found at http://www.albertgao.xyz/2018/06/07/scroll-a-not-in-view-component-into-the-view-using-react/)
Reading the spec, it was a little hard to suss out the meaning of block and inline, but after playing with it, I found that for a vertical scrolling list, block: 'end' made sure the element was visible without artificially scrolling the top of my content off the viewport. With 'center', an element near the bottom would be slid up too far and empty space appeared below it. But my container is a flex parent with justify: 'stretch' so that may affect the behavior. I didn't dig too much further. Elements with overflow hidden will impact how the scrollIntoView acts, so you'll probably have to experiment on your own.
My application has a parent that must be in view and if a child is selected, it then also scrolls into view. This worked well since parent DidMount happens before child's DidMount, so it scrolls to the parent, then when the active child is rendered, scrolls further to bring that one in view.
Solution 3
Another example which uses function in ref rather than string
class List extends React.Component {
constructor(props) {
super(props);
this.state = { items:[], index: 0 };
this._nodes = new Map();
this.handleAdd = this.handleAdd.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
handleAdd() {
let startNumber = 0;
if (this.state.items.length) {
startNumber = this.state.items[this.state.items.length - 1];
}
let newItems = this.state.items.splice(0);
for (let i = startNumber; i < startNumber + 100; i++) {
newItems.push(i);
}
this.setState({ items: newItems });
}
handleRemove() {
this.setState({ items: this.state.items.slice(1) });
}
handleShow(i) {
this.setState({index: i});
const node = this._nodes.get(i);
console.log(this._nodes);
if (node) {
ReactDOM.findDOMNode(node).scrollIntoView({block: 'end', behavior: 'smooth'});
}
}
render() {
return(
<div>
<ul>{this.state.items.map((item, i) => (<Item key={i} ref={(element) => this._nodes.set(i, element)}>{item}</Item>))}</ul>
<button onClick={this.handleShow.bind(this, 0)}>0</button>
<button onClick={this.handleShow.bind(this, 50)}>50</button>
<button onClick={this.handleShow.bind(this, 99)}>99</button>
<button onClick={this.handleAdd}>Add</button>
<button onClick={this.handleRemove}>Remove</button>
{this.state.index}
</div>
);
}
}
class Item extends React.Component
{
render() {
return (<li ref={ element => this.listItem = element }>
{this.props.children}
</li>);
}
}
Demo: https://codepen.io/anon/pen/XpqJVe
Solution 4
To build on @Michelle Tilley's answer, I sometimes want to scroll if the user's selection changes, so I trigger the scroll on componentDidUpdate
. I also did some math to figure out how far to scroll and whether scrolling was needed, which for me looks like the following:
componentDidUpdate() {
let panel, node;
if (this.refs.selectedSection && this.refs.selectedItem) {
// This is the container you want to scroll.
panel = this.refs.listPanel;
// This is the element you want to make visible w/i the container
// Note: You can nest refs here if you want an item w/i the selected item
node = ReactDOM.findDOMNode(this.refs.selectedItem);
}
if (panel && node &&
(node.offsetTop > panel.scrollTop + panel.offsetHeight || node.offsetTop < panel.scrollTop)) {
panel.scrollTop = node.offsetTop - panel.offsetTop;
}
}
Solution 5
With reacts Hooks:
- Import
import ReactDOM from 'react-dom';
import React, {useRef} from 'react';
- Make new hook:
const divRef = useRef<HTMLDivElement>(null);
- Add new Div
<div ref={divRef}/>
- Scroll function:
const scrollToDivRef = () => {
let node = ReactDOM.findDOMNode(divRef.current) as Element;
node.scrollIntoView({block: 'start', behavior: 'smooth'});
}
MindJuice
President and CEO of indie iPhone developer, Mind Juice Media.
Updated on May 18, 2020Comments
-
MindJuice about 4 years
I have a popup list which is a
div
that contains a vertical list of childdiv
s. I have added up/down keyboard navigation to change which child is currently highlighted.Right now, if I press the down key enough times, the highlighted item is no longer visible. The same thing also occurs with the up key if the view is scrolled.
What is the right way in React to automatically scroll a child
div
into view? -
MindJuice almost 9 yearsThanks, your first example is what I was thinking of, but I prefer your second example where the child nodes don't need to worry about it.
-
js-coder about 8 yearsWow,
Element.scrollIntoView()
is super awesome. -
knowuh almost 8 yearsJust a note: in React 15.x and greater you will want to use
ReactDom.findDOMNode
instead ofReact.findDOMNode
-
metakermit over 7 yearsI show another similar approach where I add an empty element at the bottom of the list to which I can always scrollIntoView in this answer.
-
jsaven over 6 yearsSimilarly, I've used npmjs.com/package/scroll-into-view to good effect. Very simple to implement. Inside the component that should be made visible: componentDidMount() { scrollIntoView(React.findDOMNode(this)) }
-
Sgnl over 6 years@jsaven I think you mean
ReactDOM.findDOMNode(this)
: reactjs.org/docs/react-dom.html#finddomnode -
Pitt over 5 yearsSetting the ref to a string is deprecated. It is recommended to use either the callback pattern or the createRef API instead.
-
gaurav5430 over 5 yearsAFAIK, the didMount of parent happens after the child stackoverflow.com/questions/32814970/…
-
eon about 5 yearsYeah, that's actually true, @gaurav5430. Don't know what I was thinking!
-
srk over 3 yearsIf you get an error that says "scrollIntoView not a function," remember to assign the
ref
to a standard DOM element such asdiv
, and not a React component. More details here. -
Elron over 3 yearsWhile this works, I find eon's answer cleaner and more up-to-date.