Answer the question
In order to leave comments, you need to log in
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
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
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
...
const Box = React.forwardRef((props, ref) => {
return <BoxElement {...props} ref={ref} />
})
...
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question