1

Hello I want to auto focus to input when my page loaded. I have to use Suspense because I using i18n. I have auto focus code but not working well.

<Suspense fallback={<LoadingScreen/>}>
  <Input />
</Suspense>
const Input = () => {
  const inputRef = useRef(null);
  useEffect(() => {
    inputRef.current.focus();
  }, []);
  return (
    <input ref={inputRef} type="text"/>
  );
};

My code working well when I remove suspense. But I need suspense for i18n. How can I fix this?

Fırat Kaya
  • 87
  • 1
  • 5

1 Answers1

1

Thy using useCallback instead of useEffect.

const Input = () => {
  const callbackRef = useCallback(ref => ref && ref.focus());
  return (
    <input ref={callbackRef} type="text"/>
  );
};

It didn't work because useEffect was called when the component is Mounted which is happens before the <Suspese /> is completed.

  • same problem :( working when re-rendering but not working after refresh the page – Fırat Kaya Dec 08 '21 at 22:18
  • Ok I see where the problem is, Suspense starts rendering as soon as fetching: https://reactjs.org/docs/concurrent-mode-suspense.html#approach-3-render-as-you-fetch-using-suspense You can try a fix with `useEffect(() => ref.current.focus(), [dataLoaded])` this will trigger the function when you change the state of the dataLoaded – Serhii Yukhnevych Dec 08 '21 at 22:38
  • I think I can create new state with redux and when LoadingScreen component unmounted I set true pageLoaded redux state. And I focus with useEffect when pageLoaded is true. Is it ok? – Fırat Kaya Dec 08 '21 at 22:49
  • I think this will work – Serhii Yukhnevych Dec 08 '21 at 23:00
  • Yeah its work, thanks – Fırat Kaya Dec 08 '21 at 23:23