How can I make it work with react hooks
utiq opened this issue · 3 comments
utiq commented
I'm trying to make it work with functional components and hooks, but it doesn't work, what I'm doing wrong?
import React, {
useRef,
useState,
useEffect
} from 'react'
import autosize from 'autosize'
const TextboxCounter = ({ ...rest }) => {
const textareaRef = useRef()
useEffect(() => {
autosize(textareaRef)
}, [])
return (
<div>
<textarea {...rest} ref={textareaRef} placeholder="Enter your comment here"></textarea>
<p>Characters Left: {charsLeft}</p>
</div>
)
}
export default TextboxCounter
mattanglin commented
@utiq You need to get the current value from the ref
https://reactjs.org/docs/hooks-reference.html#useref
import React, {
useRef,
useState,
useEffect
} from 'react'
import autosize from 'autosize'
const TextboxCounter = ({ ...rest }) => {
const textareaRef = useRef()
useEffect(() => {
// .current holds dom element
autosize(textareaRef.current)
}, [])
return (
<div>
<textarea {...rest} ref={textareaRef} placeholder="Enter your comment here"></textarea>
<p>Characters Left: {charsLeft}</p>
</div>
)
}
export default TextboxCounter
emorling commented
This works, but creates a "jumpy" experience in Chrome on OS X. You can see the textarea initializing with a default height, and then "jumping" to it's autosized height. Any ideas how to fix that?
albertcito commented
I created a component using this library https://github.com/albertcito/texarea-autosize-reactjs