I feel a bit ashamed to ask you about that because I believe it is quite straightforward to solve this issue and it is basic. But still I stuck on this.
I would like to change my styles, for ex. my backgroundColor, of my div when onscroll event fires, but this seems to be not working. While trying to set it like this backgroundColor:this.state.backgroundColor, the error appears: Cannot read property 'state' of undefined
Thanks in advance!
Here's my code:
import React, { Component } from 'react';
class Header extends Component {
constructor(props) {
super(props);
this.state = {
backgroundColor: 'black',
};
}
componentDidMount() {
const headerElement = this.refs.header;
const sticky = headerElement.offsetTop;
window.addEventListener('scroll', () => this.handleScroll(sticky));
}
handleScroll(sticky) {
if (window.pageYOffset >= sticky) {
this.setState({
backgroundColor: 'yellow'
});
}
}
render() {
const { containerStyle } = styles;
return (
<header style={containerStyle} ref='header'> {this.props.text} </header>
);
}
}
const styles = {
containerStyle: {
backgroundColor: this.state.backgroundColor,
}
};
export default Header;
No need to be ashamed to ask questions, I've yet to meet a developer who is not still a student, myself included. :)
Your styles
variable is out of scope. You need to move it into your render()
function.
See here for working code: https://codesandbox.io/s/3rynvvn18m?module=%2Fheader.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With