0

I am referencing an <h1> with ref="header". I'm trying to change CSS rules but a TypeScript error is not letting me.

const header = ref<HTMLElement | null>(null)

onMounted(() => {
  header.value.style.color = "red"
})

screenshot of error message

2
  • You could simply use optional chaining to header.value?.style.color = 'red' Commented Aug 9, 2022 at 23:52
  • I have this error doing that: The left-hand side of an assignment expression may not be an optional property access.ts(2779) Commented Aug 9, 2022 at 23:53

1 Answer 1

3

The error is perfectly reasonable: you can't be sure that that element exists. And if the element doesn't exist, the template ref's value will be null. It's actually right there in the type for the ref: HTMLElement | null.

You can change your onMounted callback to the following to check for that:

onMounted(() => {
  if (header.value)
    header.value.style.color = "red"
})
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.