1
votes

I do a form Login to Study on React... and this error i can't resolve..

TypeError: Cannot read property 'classList' of undefined

My Code Error:

changeState(){

    const {isLogginActive} = this.state;
    if(isLogginActive) {
      this.rightSide.classList.remove("right");
      this.rightSide.classList.add("left");
    } else {
      this.rightSide.classList.remove("left");
      this.rightSide.classList.add("right");
    }
    this.setState((prevState)=> ({ isLogginActive: !prevState.isLogginActive }));
  }

Some one can help me... have a one solution for this ... doing in React.

Thanks.

1
The error is clear: this.rightSide is undefined. But without a minimal reproducible example we can only guess why that is the case. - Andreas
provide the whole component - Hello Earth

1 Answers

0
votes

I am assuming that rightSide is a property defined using the createRef API.

In that case, classList is only accessible through the current attribute of the ref.

this.rightSide.current.classList

As createRef() is asynchronous, it might return null if you are accessing it early, e.g. on the componentDidMount lifecycle.

Hence, it is always safer to add an if statement to check for current

changeState(){
  const {isLogginActive} = this.state;
  if (this.rightSide.current) {
    if(isLogginActive) {
      this.rightSide.current.classList.remove("right");
      this.rightSide.current.classList.add("left");
    } else {
      this.rightSide.current.classList.remove("left");
      this.rightSide.current.classList.add("right");
    }
    this.setState((prevState)=> ({ isLogginActive: !prevState.isLogginActive }));
  }
}