2

I am trying to use the forwardRef in typescript React to access a child state. I've followed examples online but many are for javascript. I'm getting compiler errors with this.

This is the simplest version I can come up with and the compiler doesn't like the console log. It says ref.current may be undefined, so I've used some && logic but now it says getMyState() does not exist on type 'never'. I've also looked up that error as I've seen it before but don't understand it in this context.

const Parent = () => {
  const ref = useRef();
  console.log(ref.current && ref.current.getMyState());
  return(
    <>
    <Child ref={ref}/>
    </>
  );
  
}
const Child = forwardRef((props, ref) => {
  const [item, setItem] = useState('hello');
  useImperativeHandle(ref, () => ({getMyState: () => {return item}}), [item]);

  return (
    <>
    bob
    </>
  );
})

Note: I've read the React docs, my use case is a valid one for forwardRef.

Why am I getting this error and how do I extract the state from the child?

1 Answer 1

3

You need to define type for the ref with the form of functions you expose in the Child component.

Try like below.

type ChildHandle = {
  getMyState: () => string | null;
};

const Child = forwardRef((props, ref) => {
  const [item, setItem] = useState("hello");
  useImperativeHandle(
    ref,
    () => ({
      getMyState: () => {
        return item;
      }
    }),
    [item]
  );

  return <>bob</>;
});

const Parent = () => {
  const ref = useRef<ChildHandle>();
  console.log(ref.current && ref.current.getMyState());
  return (
    <>
      <Child ref={ref} />
    </>
  );
};

Example of using the handle of Child within Parent

Edit React Typescript (forked)

Sign up to request clarification or add additional context in comments.

6 Comments

@user2956284, check this out !!
This worked great thanks. Although I didn't expect the reference to be affected when the child is called multiple times. e.g. if I pass in a reference to child once and then call child 2 more times but without passing in a reference, the reference still changes. I wonder if there is a way around this as I'd like a separate reference for each instance. I can still work with this though :)
what do you mean by "call child 2 more times"? If you create two Child elements then you should pass two separate refs to them.
My bad. I'm too tired and left in some code where it shouldn't be.
Is there a way to make it not also spit out undefineds? It's working great, but my refs quickly turn to undefined. I could work around it but wondering if there is a way to do it inside the return statement of the child.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.