0

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

  • You are not consistent with the props naming, you have innerRef and forwardRef, pick one of them, `props.forwardRef` is `undefined`. Moreover initialising in the constructor is an anti-pattern, read it in React docs. The easiest way for people to help you is to make a reproducible example in a codesandbox, see [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – Dennis Vash Oct 19 '21 at 09:16
  • Also notice that `ref` prop in classes does not work as you might expect, see https://stackoverflow.com/questions/62931216/why-exactly-do-we-need-react-forwardref/62931842#62931842 – Dennis Vash Oct 19 '21 at 09:18
  • Sorry for the mistake. I have updated the question. Regarding the ref props in class components, if I was using a props called forwardRef it is similar to the innerRef that you provided in the [link](https://stackoverflow.com/questions/62931216/why-exactly-do-we-need-react-forwardref/62931842#62931842) – Arjun Vinod Oct 19 '21 at 10:05

0 Answers0