Last active
July 13, 2022 21:41
-
-
Save jeremylenz/aa12a3b8b6cda311a3c78d2b321c615e to your computer and use it in GitHub Desktop.
Use React refs to prevent automatic left scrolling on render
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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