Issue
Alright, I've read through every single thread and Github issue on this and couldn't find a real answer to why we can't console.log(ref.current)
this on Typescript.
function App() {
const ref = React.useRef<HTMLDivElement>(null);
return (
<div className="App">
<Parent ref={ref} />
</div>
);
}
export default App;
const Parent = React.forwardRef<HTMLDivElement>(({}, ref) => {
return (
<div>
<Child ref={ref}/>
</div>
);
});
export default Parent;
const Child = React.forwardRef<HTMLDivElement | null, IProps>(
(props, ref) => {
console.log(ref.current)
return <div ref={ref}>Hello World</div>;
}
);
export default Child;
I understand that ref
can be null thats why it makes sense to console.log(ref?.current)
but I dont understand why we can't access the current
even with an if
statement.
Solution
You need to assert the ref, use ref as MutableRefObject<HTMLDivElement>
as it is not necessary for every ref to have the current property.
In your parent component, use (ref as MutableRefObject<HTMLDivElement>).current
Answered By - Ritik Banger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.