user2956284
user2956284

Reputation: 63

forwardRef with typescript React

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?

Upvotes: 2

Views: 3551

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13245

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)

Upvotes: 3

Related Questions