I get this error: Cannot read property 'getBoundingClientRect' of null
. I use this function getBoundingClientRect
, because in my project I want to have the following efect: at the moment one element is highlighted, the rest has different styles. The message shows the functions handleScroll
. The component in which I use looks like this
class QuestionListItem extends Component {
constructor() {
super();
this.state = {
isActive: false,
};
this.handleScroll = this.handleScroll.bind(this);
}
componentDidMount = () => {
window.addEventListener('scroll', this.handleScroll);
this.handleScroll();
};
handleScroll = () => {
const { isActive } = this.state;
const { top } = this.wrapRef.getBoundingClientRect();
if (top > 60 && top < 400 && !isActive) {
this.setState({ isActive: true });
}
if ((top <= 60 || top >= 400) && isActive) {
this.setState({ isActive: false });
}
}
setWrapRef = (ref) => {
this.wrapRef = ref;
}
render() {
const { isActive } = this.state;
const { question } = this.props;
return (
<div
className={`Test__questions-item--noactive ${isActive && 'Test__questions-item--active'}`}
ref={this.setWrapRef}
>
<li key={question.id}>
<p>
{question.question}
</p>
<QuestionAnswerForm name={question.question} />
</li>
</div>
);
}
}
Why is there such a mistake? Thanks for the help in advance :)