Search code examples
reactjsstyled-components

React ref in ref


I use a react-textarea-autosize that is wrapped in a styled-component, like so:

import React from 'react'
import styled from 'styled-components'
import TextareaAutosize from 'react-textarea-autosize'

const MyTextArea = styled(TextareaAutosize)``

function Component() {
  return (
    <MyTextArea innerRef={...} />
  )
}

I need to get the reference for the underlying html textarea element. However, to get to it I need to:

  • The TextareaAutosize component can be accessed via the styled-components' innerRef prop - <MyTextArea innerRef={textareaResizeable => ...} />
  • The html textarea element can be accessed via the react-textarea-autosize' inputRef prop - <TextareaAutosize inputRef={textarea => ...} />

I understand these two separate steps. But how do I access the textarea html element directly from MyTextArea component?


Solution

  • I found the answer here. So, in my case the solution looked like this:

    import React from 'react'
    import styled from 'styled-components'
    import TextareaAutosize from 'react-textarea-autosize'
    
    const MyTextArea = styled(
      ({_ref, ...props}) => <TextareaAutosize inputRef={_ref} {...props} />
    )``
    
    class Component extends React.Component {
      render() {
        return (
          <MyTextArea innerRef={node => this.textarea = node} />
        )
      }
    }
    

    then use this.textarea wherever you need.