Skip to content

Instantly share code, notes, and snippets.

@sikanhe
Last active May 16, 2023 04:28
Show Gist options
  • Save sikanhe/015c606710dc656f0c40 to your computer and use it in GitHub Desktop.
Save sikanhe/015c606710dc656f0c40 to your computer and use it in GitHub Desktop.
Simple textarea that expand and shrinks depending on the content
import React, { PropTypes } from 'react'
export default class TextareaAutosize extends React.Component {
static propTypes = {
value: PropTypes.string,
className: PropTypes.string,
style: PropTypes.object,
onChange: PropTypes.func
}
componentDidMount() {
const textarea = this.refs.textarea
textarea.style.height = textarea.scrollHeight + 'px'
}
handleChange = e => {
const textarea = this.refs.textarea
textarea.style.height = 0 // has to set to 0 for shrinking
textarea.style.height = textarea.scrollHeight + 'px'
this.props.onChange(e.target.value)
}
render = () => (
<textarea
{...this.props}
ref="textarea"
rows="1"
onChange={this.handleChange}
/>
)
}
@moodysalem
Copy link

Would making those two mutations reset your scroll position in some browsers?

Specifically:

textarea.style.height = 0 // has to set to 0 for shrinking
textarea.style.height = textarea.scrollHeight + 'px'

@moodysalem
Copy link

You can render a component twice and just hide one of the renderings so you're not resizing the input the user is manipulating

https://gist.github.com/moodysalem/52601c137109cf87434b

@sikanhe
Copy link
Author

sikanhe commented May 1, 2017

@moodysalem interesting approach

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