1

I want to get height and width of styled component in react. I am using this https://opensourcelibs.com/lib/use-resize-observer and my code looks like:

const Test = ({className, ref}) => {
    return (
        <div className={className} ref={ref}/>
    )
}

const StyledTest = styled(Test)`
  height: 100px;
  width: 100px;
  background-color: greenyellow;
`


const TestClass = () => {
    const testRef = useRef(null)
    const testSize = useResizeObserver({ref: testRef});

    return (
        <React.Fragment>
            <ThemeProvider theme={testTheme}>
                <h1>Height test: {leftContainerSize.height}</h1>
                <StyledTest ref={leftContainerRef}/>
            </ThemeProvider>
        </React.Fragment>
    )
}

Unfortunately it doesn't work. If I try to do the same for example with image it works so I think there are problem with passing ref into styled components. I read this article Using 'ref' on React Styled Components is not working, but I don't know how to use innerRef in my case. I also tried to use forwardRef but I failed too. Does someone know to make it work?

Pawelsar1
  • 83
  • 1
  • 3
  • 9

1 Answers1

0

Try this.

Use forwardRef in functional component to get ref. Don't try to get ref from props.

Your example is missing variables: leftContainerRef, leftContainerSize. Although you are trying to use them.

const Test = forwardRef(({ className }, ref) => {
    return (
        <div className={className} ref={ref} />
    )
})

const StyledTest = styled(Test)`
  height: 100px;
  width: 100px;
  background-color: greenyellow;
`


const TestClass = () => {
    const { ref, height } = useResizeObserver();

    return (
        <React.Fragment>
            <ThemeProvider theme={testTheme}>
                <h1>Height test: {height}</h1>
                <StyledTest ref={ref} />
            </ThemeProvider>
        </React.Fragment>
    )
}

If you want to work with the ref. You can create your ref and pass it to the hook.

const Test = forwardRef(({ className }, ref) => {
    return (
        <div className={className} ref={ref} />
    )
})

const StyledTest = styled(Test)`
  height: 100px;
  width: 100px;
  background-color: greenyellow;
`


const TestClass = () => {
    const ownRef = useRef(null)
    const { height } = useResizeObserver({ ref: ownRef });

    return (
        <React.Fragment>
            <ThemeProvider theme={testTheme}>
                <h1>Height test: {height}</h1>
                <StyledTest ref={ownRef} />
            </ThemeProvider>
        </React.Fragment>
    )
}
Ivan Popov
  • 656
  • 2
  • 10