Home > Blockchain >  how to focus input element when page renders in React
how to focus input element when page renders in React

Time:02-07

export const InputComponent = () => {
  const inputRef = useRef<HTMLInputElement | undefined>();

  useEffect(() => {
    inputRef.current.focus();
  }, [inputRef]);

  return(<input type="text" ref={inputRef})
}

whats wrong in my code. Please help me.

CodePudding user response:





export const InputComponent = () => {
  const inputRef = useRef<HTMLInputElement | undefined>(null);

  useEffect(() => {
    inputRef.current.focus();
  }, [inputRef]);

  return(<input type="text" ref={inputRef})
}

Try using this code . check this codesandbox

CodePudding user response:

You missed the closing bracket for the input tag.

return <input type="text" ref={inputRef} />
  •  Tags:  
  • Related