B
B
bingumd2020-09-23 09:28:15
React
bingumd, 2020-09-23 09:28:15

How to fix 'Function components cannot be given refs' error?

There is this component:

import PropTypes from 'prop-types'
import styled from 'styled-components'
import { flexbox } from 'styled-system'

const BoxElement = styled.div`
    ${flexbox};
`

const Box = ({ children, ...props }) => <BoxElement {...props}>{children}</BoxElement>

Box.propTypes = {
    as: PropTypes.oneOf(['div', 'section']),
}

Box.defaultProps = {
    as: 'div',
}

export default Box


And I use it in another component:
import React, { useRef } from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import Box from './Box'

export const HeroWrap = styled(Box)`
    position: relative;
`

const Hero = ({ children, ...props }) => {
    const elRef = useRef(null)
    
    return (
        <HeroWrap ref={elRef} {...props}>
            {children}
        </HeroWrap>
    )
}

Hero.propTypes = {
    children: PropTypes.node.isRequired,
}

Hero.defaultProps = {
    as: 'section',
}

export default Hero


And I get an error:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?


How can I fix it?

UPD
Problem solved. In order to use refs in a functional component, you need to create it like this:
...
const Box = React.forwardRef((props, ref) => {
    return <BoxElement {...props} ref={ref} />
})
...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2020-09-23
@bingumd

  1. Read message.
  2. Translate it.
  3. Make the Box component based on a class, not a function.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question