nikjohn
nikjohn

Reputation: 21850

Using 'ref' on React Styled Components is not working

I am having difficulty using refs with Styled Components. When I try to access them in my class methods like below, I get the following error:

Edit.js:42 Uncaught TypeError: this.....contains is not a function

  constructor(props) {
    ....
    this.setWrapperRef = this.setWrapperRef.bind(this);
    this.handleClickOutside = this.handleClickOutside.bind(this);
   }
----------
  setWrapperRef = (node) => {
    this.wrapperRef = node;
  }
  handleEdit = (e) => {
    e.preventDefault();
    this.props.onEdit(this.props.id, this.state.title);
  }
----------
<Wrapper onSubmit={this.handleEdit} ref={this.setWrapperRef}>
  ...
</Wrapper>

I found the code from this question

What am I doing wrong here?

Upvotes: 31

Views: 39903

Answers (3)

SID JO
SID JO

Reputation: 11


    const StyledComponent = styled.div.attrs(({ref}) => ({
      ref: ref,
    }))``

    const App = () => {
      const anyRef = useRef();

      return <StyledComponent ref={anyRef}/>
    };

Upvotes: 0

mkg
mkg

Reputation: 779

If you extend another component in styled ref forwarding requires efford. so my solution was extending that component with as prop.

before:

import { useRef } from 'react'
import styled from 'styled-components'

const Card = styled.div``
const Block = styled(Card)``

const Component = () => {
    const ref = useRef(null);
    return <Card ref={ref} />
}

after:

import { useRef } from 'react'
import styled from 'styled-components'

const Card = styled.div``
const Block = styled.div``

const Component = () => {
    const ref = useRef(null);
    return <Block as={Card} ref={ref} />
}

Upvotes: 3

nikjohn
nikjohn

Reputation: 21850

I found the answer myself. The solution is to use innerRef instead of ref as the ref itself points to the Styled Component and not the DOM node.

A detailed discussion can be found on GitHub

Upvotes: 38

Related Questions