Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
In my component, I have the following code to scroll to the bottom of the page:
const el = useRef(null);
useEffect(() => {
if (el.current === null) { }
el!.current!.scrollIntoView({ block: 'end', behavior: 'smooth' });
if (props.loading != true)
props.fetchFeedbackTaskPageData(submissionId);
}, [])
This el
ref is attached to a div (at the bottom of the page) like this:
<div id={'el'} ref={el}></div>
However, I am receiving the following error:
Property 'scrollIntoView' does not exist on type 'never'. TS2339
When I was not using !
, I was receiving this error:
Object is possibly 'null'. TS2531
I checked many posts on this issue but did not see how to handle this in react when using useRef
and scrollIntoView
. Any ideas?
–
–
You have to tell useRef what types other than null it will be assigned to, e.g. useRef<null | number>(null)
or in your case useRef<null | HTMLElement>(null)
.
The problem is that by assigning null as a default value to the ref, typescript can only guess that the type of the ref will be that of it's initial value (null) - which is why you're getting the errors you mentioned. Generally speaking, refs don't have to be DOM components, so useRef's type definition does not assume that it will be assigned to one.
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.