Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React function not activating

Tags:

reactjs

In React i have window.onscroll function that when scrolled down should activate change function that sets setState classAnimation to 'testing2'.

For some reason change function does not activate. it gives TypeError: Cannot read property 'change' of undefined.

My end goal is to add class called testing2 to state property and change the onscreen text to red when user scrolls down more then 50px.

Help would be nice.

APP.JS

import React, { Component } from 'react';
import './App.css';
import Animations from './components/animations';


class App extends Component {

  constructor(props){
    super(props);

this.state = {
  classAnimation: '' 
};

this.change = this.change.bind(this);

}


change = () => {
    this.setState({
      classAnimation: 'testing2'
    });
}



  componentDidMount() {
    window.onscroll = function() {myFunction()};

    function myFunction() {
      if (document.body.scrollTop > 50 || document.documentElement.scrollTop 
> 50) {
      this.change();
  } else {

      }
    }
   }


  render() {
    return (
      <div className="App">
        <Animations testing={this.state.classAnimation}/>

      </div>
    );
  }
}

export default App;

ANIMATION.JS

import React from 'react';

const Home = (props) => {

    return(
        <div>
                <div className={props.testing}>very good test it is</div>
        </div>
        );
    };

export default Home;   

APP.CSS

    body{
  height:1500px;
}

#myP{
  position:fixed;
}


.testing2{
  position:fixed;
  color:red;
}

THIS IS WHAT I GET:

TypeError: Cannot read property 'change' of undefined

THIS IS WHAT I WANT:

Changing text called Lorem ipsum dolor sit amet, consectetur adipiscing elit to red when user has scrolled down.

like image 854
Pleinair Avatar asked Mar 30 '26 00:03

Pleinair


1 Answers

There are two main problems here.

Setting the scroll events should go like this:

myFunction = () => {
    //your logic
}

componentDidMount(){
    window.addEventListener('scroll', this.myFunction)
}

componentWillUnmount(){
    window.removeEventListener('scroll', this.myFunction)
}

You are binding an arrow function(lexical this). Either use class method notation or arrow functions without bind:

change = () =>{/* Don't bind this */}

change(){/* Should be binded in `constructor` */}
like image 164
Dupocas Avatar answered Apr 02 '26 03:04

Dupocas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!