Home > Back-end >  How to use state information with className in react?
How to use state information with className in react?

Time:11-14

I have two CSS classes named .Toolbar and .Toolbarnew, upon scrolling after window.scrolly>200 i want my div to be style as per .Toolbarnew and before 200 to be styled as per .Toolbar (i am using css module)

Here is my code:

import React ,{Component} from 'react';

import classes from './Toolbar.css';


class Toolbar extends Component{
    state={
        name:'Toolbar'
    }

    listenScrollEvent = e => {
        console.log(window.scrollY);
        if (window.scrollY > 200) {
          this.setState({name: 'Toolbarnew'})
        } else if(window.scrollY < 200) {
          this.setState({name: 'Toolbar'})
        }
    }

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


    render(){

        return(
            <div className={classes.this.state.name}>
                {this.props.children}
            </div>    

        )
    }
}

export default Toolbar;

I hardcoded className={classes.Toolbar} and wrote console.log(this.state.name) after render() to check if the value is being updated. It turns out that the value was successfully being updated.

But when i use className={classes.this.state.name} i get the error message as TypeError: Cannot read properties of undefined (reading 'state')

Can anyone help me on how to resolve this problem?

CodePudding user response:

Write this:

<div className={classes[this.state.name]}>
 {this.props.children}
</div>   

You are getting error: TypeError: Cannot read properties of undefined (reading 'state')

Because you are trying to access the property this in classes which does not exist (undefined).

Instead use class name dynamically, classes[this.state.name]. This means you are accessing property name (which is set in this.state.name) in classes defined in object i.e. classes["Toolbar"] => classes.Toolbar

  • Related