Home > Back-end >  React - useImperativeHandle exposed properties are overlapped
React - useImperativeHandle exposed properties are overlapped

Time:11-29

I am creating a component "UsernameInput", that renders my custom "TextInput" component:

const UsernameInput = forwardRef(
  (
    {
      ...
    },
    ref
  ) => {
     ...
     
     return <TextInput ref={ref} />
  });

My TextInput component exposes some functionality to its parents:

const TextInput = forwardRef(
  (
    {
      ...
    },
    ref
  ) => {
      ...

      useImperativeHandle(
        ref,
        () => ({
          getText: () => text,
          setText,
          focus,
          blur,
      }),
      [text]
    );

    ...
  });

Now... in my UsernameInput component, I want to expose other functionalities too...

const UsernameInput = forwardRef(
  (
    {
      ...
    },
    ref
  ) => {
     ...

     useImperativeHandle(
       ref,
       () => ({
         getUsernameInformation: () => usernameInformation,
       }),
       [usernameInformation]
     );

     return <TextInput ref={ref} />
  });

The main problem I am experiencing is that, if I do the following:

const usernameInputRef = useRef(null);

const handleOnSubmit = () => {
    usernameInputRef.current.blur()
}

return (
   <UsernameInput ref={usernameInputRef} ...
);

The code throws me an exception ".blur() is undefined".

It seems that, because of having two useImperativeHandle, the exposed functionalities are overlapped.

Any ideas on how to solve this problem?

CodePudding user response:

Based on @Amila Senadheera comment:

   const textInputRef = useRef(null);
    
   ...

   useImperativeHandle(
      ref,
      () => ({
        getUsernameInformation: () => usernameInformation,
        ...textInputRef.current,
      }),
      [usernameInformation]
    );

    ...

    return <TextInput ref={textInputRef} ... />
  • Related