Skip to content

Instantly share code, notes, and snippets.

@jeremylenz
Last active July 13, 2022 21:41
Show Gist options
  • Save jeremylenz/aa12a3b8b6cda311a3c78d2b321c615e to your computer and use it in GitHub Desktop.
Save jeremylenz/aa12a3b8b6cda311a3c78d2b321c615e to your computer and use it in GitHub Desktop.
Use React refs to prevent automatic left scrolling on render
import React from 'react';
import styled from 'styled-components'
import MyHorizonalScrollingComponent from './MyHorizontalScrollingComponent'
const StyledDiv = styled.div`
overflow-x: scroll;
overflow-y: visible;
`
class MyHorizonalScrollingComponent extends React.Component {
constructor(props) {
super(props);
this.scrollRef = React.createRef(); // Create a reference so that later, we can read & write scrollLeft
}
getSnapshotBeforeUpdate(prevProps, prevState) {
const scrollRef = this.scrollRef.current;
if (scrollRef && scrollRef.scrollLeft) {
// Before the component updates, capture the current scrollLeft value.
return scrollRef.scrollLeft
}
return null
}
componentDidUpdate(prevProps, prevState, snapshot) {
const scrollRef = this.scrollRef.current; // Access the ref we created above
if (scrollRef) {
// Write the retrieved scrollLeft value to the DOM element.
// If scrollLeft was anything but 0, this will preserve the current horizonal scroll position
// and avoid auto-scrolling all the way to the left on every render!
scrollRef.scrollLeft = snapshot;
// console.log(snapshot)
}
}
render () {
return (
<React.Fragment>
<StyledDiv />
</React.Fragment>
)
}
}
export default MyHorizonalScrollingComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment