Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I make it work with react hooks #383

Open
utiq opened this issue Sep 12, 2020 · 3 comments
Open

How can I make it work with react hooks #383

utiq opened this issue Sep 12, 2020 · 3 comments

Comments

@utiq
Copy link

utiq commented Sep 12, 2020

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
Copy link

mattanglin commented Oct 17, 2020

@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
Copy link

emorling commented Oct 23, 2020

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
Copy link

I created a component using this library https://github.com/albertcito/texarea-autosize-reactjs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants