Using 'ref' on React Styled Components is not working Using 'ref' on React Styled Components is not working reactjs reactjs

Using 'ref' on React Styled Components is not working


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


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} />}