React Refs undefined inside functions and has values outside

Viewed 34

I am having a lot of troubles working with react refs, what i want is to use a function declared in another components

the below code is what i am doing:

const Component1 = (props, ref) => {
  const getText = () => {};
  React.useImperativeHandle(ref, () => ({ getText }));
  return <div />;
};
export default React.forwardRef(Component1);

const Component2 = (props) => {
  const component1Ref = React.createRef();
  const getTextFromComponent1 = () => {
    console.log({ component1Ref }); //will be equal to {current:null}
  };
  console.log({ component1Ref }); //will be equal to {current:{getText}}

  return <Component1 ref={component1Ref} />;
};
export default Component2;

It is very weird, the value inside getTextFromComponent1 was the same as outside, it suddenly broke! this happened with me many times

Anyone has a clue of the solution? Features are breaking without any change

Thanks in advance Hanan

1 Answers

It will take some time for ref to be initialized. I have shown an example to call it from a click event handler and within a useEffect hook.

Following works without any issues:

const Component1 = React.forwardRef((props, ref) => {
  const textRef = React.createRef();
  const getText = () => {
    return textRef?.current?.value;
  };
  React.useImperativeHandle(ref, () => ({ getText }));
  return <input ref={textRef} defaultValue="sample text" />;
});

const Component2 = (props) => {
  const component1Ref = React.createRef();

  React.useEffect(() => {
    getTextFromComponent1();
  }, []);

  const getTextFromComponent1 = () => {
    console.log(component1Ref.current?.getText());
  };

  return (
    <div>
      <button onClick={getTextFromComponent1}>Check text</button>
      <br />
      <Component1 ref={component1Ref} />
    </div>
  );
};

export default Component2;

Working Demo

Edit youthful-elbakyan-iwu2r8

Related