0

I'm trying to focus a text input field once the user clicks a button. The code looks as follows:

const refName = React.useRef();

const changeFocus = () => {
    refName.current.focus();
}

with the text input having an attribute ref defined as refName. This gives me an error (undefined is not an object (evaluating 'refName.current.focus')), and when I rewrite the changeFocus function as console.log(refName) this is what I get:

Object {
  "current": undefined,
}

I'm not sure how else I'm supposed to define the reference or how else to approach this problem. Thanks

2
  • 1
    Does this answer your question? React useRef is undefined Commented Jan 24, 2021 at 15:54
  • Can you share the full component? Commented Jan 24, 2021 at 16:16

1 Answer 1

2

You initialize your ref without a value, so there will be a moment that ref.current is undefined before it gets the value of the component that you attach it to.

You need to make your function call conditional so that it only happens if ref.current has been set:

const changeFocus = () => {
    refName.current?.focus();
}

You also need to declare the expected type for the ref, since it cannot be inferred from an initial value. The type could be the type of the specific component or it could be this:

interface Focusable {
  focus(): void;
}
const refName = React.useRef<Focusable>();

That should fix errors that you get when setting the ref property on the component.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.