Home > database >  forwardRef with typescript React
forwardRef with typescript React

Time:02-23

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?

CodePudding user response:

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} />
    </>
  );
};
  • Related