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')
CodePudding user response:
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()} />
CodePudding user response:
- onClick calls the return value of the argument you passed in
That's what it is