0

I'm learning React so sorry if the question is silly. Anyway, I'm trying to change the text of an Input element if the filtered variable is null, so I did:

const contactContext = useContext(ContactContext);
const text = useRef<HTMLInputElement>(null);

const { filterContacts, clearFilter, filtered } = contactContext;

useEffect(() => {
    if (filtered === null) {
        text.current?.value = '';
    }
});

but on this line: text.current?.value = '';

I get:

The left-hand side of an assignment expression may not be an optional property access.

what I did wrong?

UPDATE

return (
        <form>
            <input
                ref={text}
                type="text"
                placeholder="Filter Contacts..."
                onChange={onChange} />
        </form>
    )
3
  • Are you using controlled input or uncontrolled? Commented Oct 9, 2020 at 13:33
  • @AgustinMoles I have update the question showing the input return Commented Oct 9, 2020 at 13:34
  • 2
    The error is literally telling you to change text.current?.value = ''; to if(text.current){ text.current.value = ''; }. Whether or not it's necessary to use a ref is different matter. Commented Oct 9, 2020 at 13:37

1 Answer 1

4

Error message is pretty clear about what's wrong in your code.

Optional-chaining is not valid on the left-hand side of the assignment statement and you get this error because of the following statement in the useEffect hook

text.current?.value = '';

You can only use optional-chaining on the right-hand side of an assignment.

You can replace your optional-chaining code to an if statement

if (text.current) {
   text.current.value = '';
}
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.