Search code examples
reactjsuse-ref

ref.current.focus() is null


I have a icon and a input field. While onclick on icon i need to focus on the input.

Code:

const inputRef = useRef(null)

Icon:

<ChatIcon className="btn" onClick={inputRef.current.focus()} />

Input:

  <input
    placeholder="add a comment..."
    type="text"
    value={comment}
    ref={inputRef}
    onChange={(e) => setComment(e.target.value)}
  />

Error:

TypeError: Cannot read properties of null (reading 'focus')


Solution

  • You are calling the function before its click you need to add it like this

    <ChatIcon className="btn" onClick={inputRef.current.focus} />
    

    or if you wanna be safer

    <ChatIcon className="btn" onClick={() => inputRef.current && inputRef.current.focus()} />