ho-s
ho-s

Reputation: 89

Cannot read property 'style' of null in React

I want to make this work. the same thing is work but this not works.
check this out.
as you can see, the backgroundScrollis OK its working,
but a while later, i add sth, its not working .below is error message.
Uncaught TypeError: Cannot read property 'style' of null at eval

import React, { createRef, PureComponent } from 'react';

class History extends PureComponent {

    backgroundScroll = createRef()
    sth=createRef() //error

    handelScroll = () => {
      let scrollTop = document.body.scrollTop
      this.backgroundScroll.current.style.backgroundPositionY = `${scrollTop / 3}px`
    }
    
    clickRight=()=>{
        this.sth.current.style.animation='opacityChange 2s'
    }
    
    componentDidMount() {
        window.addEventListener('scroll', this.handelScroll);
    }
    
    componentWillUnmount() {
        window.removeEventListener('scroll', this.handelScroll);
    }
    
    render() {
      return (
          <>  
              {this.state.picture && 
              <div>
                  <div ref={this.sth} onClick={this.clickRight}></div>
              </div>
              }
              <header ref={this.backgroundScroll}><header>
           </>
           )

    }
}
export default History

Upvotes: 1

Views: 1187

Answers (2)

Martin Z
Martin Z

Reputation: 228

The point of the constructor is not to solve the problem, rather a best practice that you should from now put the refs in there, as I showed in my earlier comment.

Try this in your clickRight-method:

clickRight = () => {
    if(this.state.picture) {
        this.sth.current.style.animation='opacityChange 2s'
    }
}

Upvotes: 1

Martin Z
Martin Z

Reputation: 228

I feel like some code are missing here, since you're referring to this.state.picture in the render method. My guess is that the clickRight method tries to access the sth.style property when it doesn't reference a dom-element (I.E if this.state.picture doesn't exist, the div including the sth ref won't be rendered.

First of all I would move the creation of the refs to the constructor:

class History extends PureComponent {
constructor() {
    super();
    this.backgroundScroll = createRef();
    this.sth = createRef();
    }
}

Then try to remove the conditional render and see if it works.

Upvotes: 0

Related Questions