score:0

I think the problem is you have not created any ref for wrapRef. as the Error says cannot get the property of null; so the wrapRef itself is null

class QuestionListItem extends Component {
  constructor() {
    super();
    this.state = {
      isActive: false,
    };

    this.handleScroll = this.handleScroll.bind(this);
  }

  componentDidMount = () => {
    window.addEventListener('scroll', this.handleScroll);
    this.handleScroll();
  };

  wrapRef=React.createRef();

  handleScroll = () => {
    const { isActive } = this.state;
    const { top } = this.wrapRef.current.style;
    if (top > 60 && top < 400 && !isActive) {
      this.setState({ isActive: true });
    }
    if ((top <= 60 || top >= 400) && isActive) {
      this.setState({ isActive: false });
    }
  }

  render() {
    const { isActive } = this.state;
    const { question } = this.props;
    return (
      <div
        className={`Test__questions-item--noactive ${isActive && 'Test__questions-item--active'}`}
        ref={this.wrapRef}
      >
        <li key={question.id}>
          <p>
            {question.question}
          </p>
          <QuestionAnswerForm name={question.question} />
        </li>
      </div>
    );
  }
}

score:2

As I noticed your code, there you used arrow function with componentDidMount.

It should be:

componentDidMount() {}

also if you are using arrow function with handleScroll then there is no need to bind in the constructor, try to remove it and then modify the handleScroll as follows:

handleScroll = () => {
    const { isActive } = this.state;
    if (this.wrapRef) {
       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 });
       }
    }
  }

Also remove function call this.handleScroll() after event listner in the componentDidMount as it is of no use.


Related Query

More Query from same tag