Skip to content

Instantly share code, notes, and snippets.

@peterholak
Last active June 3, 2022 09:04
Show Gist options
  • Save peterholak/3b9f728c1df50214c8cd7fde4946d58a to your computer and use it in GitHub Desktop.
Save peterholak/3b9f728c1df50214c8cd7fde4946d58a to your computer and use it in GitHub Desktop.
React textarea component that scrolls to the bottom whenever its content changes
/*
Copyright 2017 Peter Holak
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import * as React from 'react'
type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
class AutoScrollingTextarea extends React.Component<TextareaProps & { autoScroll?: boolean }, {}> {
element: HTMLTextAreaElement|null
componentDidMount() {
if (this.element && this.props.autoScroll !== false) {
this.element.scrollTop = this.element.scrollHeight
}
}
componentDidUpdate(prevProps: TextareaProps, prevState: {}) {
if (prevProps.value !== this.props.value && this.element && this.props.autoScroll !== false) {
this.element.scrollTop = this.element.scrollHeight
}
}
render() {
return <textarea {...this.props} ref={e => this.element = e} />
}
}
export default AutoScrollingTextarea
@fbricon
Copy link

fbricon commented Jun 2, 2022

@peterholak looks like a neat, working solution that I may be able to reuse. However, this code is not licensed, so not open source. Would you mind adding a copyright header to your gist linking to a preferably permissive license like ASL2 or MIT? Thanks!

@peterholak
Copy link
Author

@fbricon Sure, added MIT license header

@fbricon
Copy link

fbricon commented Jun 3, 2022

@peterholak thank you very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment