Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing style property with setState in React

Tags:

css

reactjs

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;
like image 224
Murakami Avatar asked Feb 03 '18 19:02

Murakami


1 Answers

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

like image 114
Barry McGee Avatar answered Nov 08 '22 09:11

Barry McGee