Reputation: 63
I'm running React 16.8, I have a functional component that I need to measure the height of (so i can know how many children to display in the vertical space), looks like the best way to do so is with refs, but everything I've attempted so far results in the same warning: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
.
I've tried following examples online to use .forwardRef but I must not be setting it up correctly. Any help appreciated.
Here's the relevant code:
import React, { useState, useEffect, useRef } from 'react'
const ForwardingStyledDayGrid = React.forwardRef((props, ref) => (
<StyledDayGrid ref={ref}>{props.children}</StyledDayGrid>
))
function DayGrid(props) {
const [height, setHeight] = useState(0)
const dayGridRef = useRef(null)
useEffect(() => {
setHeight(dayGridRef.current.clientHeight)
})
return (
<ForwardingStyledDayGrid
ref={dayGridRef}
inCurrentMonth={props.inCurrentMonth}
>
{children}
</ForwardingStyledDayGrid>
)
}
export default DayGrid
and here's StyledDayGrid:
import React from 'react'
import styled from 'styled-components'
import withTheme from '@material-ui/core/styles/withTheme'
import Grid from '@material-ui/core/Grid'
const StyledDayGrid = withTheme(styled(({ inCurrentMonth, ...rest }) => (
<Grid {...rest} />
))`
&& {
overflow: hidden;
padding: 2px;
background-color: ${props =>
!props.inCurrentMonth && props.theme.monthView.nonCurrentMonth};
etc.....
}
`)
Upvotes: 3
Views: 1311
Reputation: 82096
As per the warning, and as explained in the docs, Functional components don't support the ref
attribute as they don't have instances like class components.
You are on the correct path with forwardRef
, however, it needs to be used on the Function Component directly, in this case StyledDayGrid
e.g.
const StyledDayGrid = React.forwardRef((props, ref) => {
// use 'ref' internally
return (...);
});
function DayGrid(props) {
const dayGridRef = useRef(null)
...
return (
<StyledDayGrid ref={dayGridRef}>
{children}
</StyledDayGrid>
)
}
Upvotes: 1