Answer the question
In order to leave comments, you need to log in
Why is my ref's current property null?
Hello, the problem is as follows:
there is a component A:
function А(...) {
const anchorRef = React.createRef<HTMLDivElement>();
return (
<div
className="Blabla"
ref={anchorRef}
>
...
<B anchorRef={anchorRef} />
...
class B extends React.Component {
...
public render() {
...
console.log('-->', this.props.anchorRef);
return (
...
<Abc someprop = {this.props.anchorRef}
...
Answer the question
In order to leave comments, you need to log in
At the time render is called, the elements have not yet been created or added to the DOM, so ref is null. You can get ref after mounting:
class B extends React.Component {
componentDidMount() {
console.log(this.props.anchorRef);
}
}
function A {
const anchorRef = useRef<HTMLDivElement>(null);
// ...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question