I'm currently receiving the following error in my React app:
Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
How can I fix this using forwardRef()?
My code is as follows:
const Services: FunctionComponent = (): ReactElement => {
const servicesRef = useRef(null);
return (
<Layout>
<ServicesList ref={servicesRef} />
</Layout>
);
};
export default Services;
const ServicesList: React.FunctionComponent = ({ children }: Props) => {
return (
<section className="my-24 md:my-32">
{children && children}
</section>
);
};
export default ServicesList;
function Parent(){
const childRef = React.useRef(null)
// do something with your childRef
React.useEffect(()=> { childREf.current.focus() },[])
return( <div> <Child ref={childRef} /> </div>)
}
const Child = React.forwardRef((props, ref) => {
console.log(ref.current)
return( <div tabIndex={1} ref={ref}> child </div)
})
React docs explain well..
https://reactjs.org/docs/forwarding-refs.html
Wrap your component with React.forwardRef and set the ref to the intended DOM element
const FancyButton = React.forwardRef((props,ref)=>(
<buttonref={ref} className="FancyButton">
{props.children}
</button>)
);