I have the folowing part of code:
private rootRef = React.createRef<HTMLDivElement>();
const target = (
<div>
<Icon design='accepted' size='xl' />
</div>
);
return (
<React.Fragment>
{React.cloneElement(target, {
ref: this.rootRef,
onMouseOver: this.handleMouseOver,
onMouseLeave: this.handleMouseLeave,
})}
{open && this.renderTooltip()}
</React.Fragment>
);
When target with div element (or any other instead of div) everything is ok, but when target is:
const target = (
<Icon design='accepted' size='xl' />
);
I get error: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Icon is a span element inside of which is svg.
I will be very appreciate for any help.
I have the same problem
I've solved this problem by updating styled-components library up to 4 version
I have the same problem. Any update on that?
"styled-components": "^4.2.0",
"react-dom": "^16.8.6",
"react": "^16.8.6",
I found this tutorial and it solved for me. But actually it is in React docs too, but not too clear for me.
[EDIT]
For redux, see this question at SOF
Here, you can also try this solution its work fine for me.
It will not generate an error of Function components cannot be given refs.
/* Child.jsx */
import React from 'react'
class Child extends React.Component {
componentDidMount() {
const { childRef } = this.props;
childRef(this);
}
componentWillUnmount() {
const { childRef } = this.props;
childRef(undefined);
}
alertMessage() {
window.alert('called from parent component');
}
render() {
return <h1>Hello World!</h1>
}
}
export default Child;
/* Parent.jsx */
import React from 'react';
import Child from './Child';
class Parent extends React.Component {
onClick = () => {
this.child.alertMessage(); // do stuff
}
render() {
return (
<div>
<Child childRef={ref => (this.child = ref)} />
<button onClick={this.onClick}>Child.alertMessage()</button>
</div>
);
}
}
/* Child.jsx */
import React from 'react'class Child extends React.Component {
componentDidMount() {
const { childRef } = this.props;
childRef(this);
}
componentWillUnmount() {
const { childRef } = this.props;
childRef(undefined);
}
alertMessage() {
window.alert('called from parent component');
}
render() {
return
Why are there two down votes?
Most helpful comment
Here, you can also try this solution its work fine for me.
It will not generate an error of Function components cannot be given refs.