I was trying to pass a callback function to the ref object of a component which uses forward ref to pass to a class component. I have noticed that the callback function is only triggered once, so I am not able to get the changes in the Element.
I am not sure what the issue is could you please help me with this.
The component to which I am passing the ref
class ElemComponent extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
};
this.ElemComponentRef = props.forwardRef || React.createRef();
}
render() {
return (
<div ref={this.ElemComponentRef}>
Div has a ref
</div>
)
}
}
export default React.forwardRef((props, ref) => <ElemComponent
forwardRef={ref} {...props}
/>);
My parent component
const App = () => {
const [value, setValue] = React.useState("");
return (
<>
<button
onClick={() => {
setValue("white" + value);
}}
>
Click
</button>
<MyForwardElement
value={value}
ref={() => console.log("this is the ref")}
/>
</>
);
};
this.ElemComponentRef = props.forwardRef || React.createRef();
Removing the above code to
<div ref={this.props.forwardRef}>
is solving my issue but I need the ref object even if it is not passed
I can't really updated the child component to a functional component right now, if there is any fix/explanation for this it would be really helpful.
Thank you