Search code examples
reactjsstyling

Change css styles from a function in ReactJs


When we try to update style of a class we use css() method in a function in jquery So i want to update a style of a class in Reactjs. Help me to do im new to React

Here is what im trying to do

    class Someclass extends Component {
      functionA= () =>{
          this.functionB();
      }
      functionB = () =>{
           //Here i want to update styles
          this.divstyle = {
          width: 80%;
          }
}
    render(){
     return(
       <div className="div_wrapper" onLoad={this.functionA()}>
          <div clasName="innerDiv" style={this.divstyle}></div>
       </div>
     )
    }
}
export default Someclass;

Solution

  • You need to define state for divstyle like below

    class Someclass extends Component {
          state = {
            divstyle : { color: 'blue' }
          }
          functionA= () =>{
              this.functionB();
          }
          functionB = () =>{
              // Call setState method to update the state.
              this.setState({
               divstyle : {
                 ...this.state.divstyle,
                  width: 80%
               })
       }
        render(){
         return(
           <div className="div_wrapper" onLoad={this.functionA()}>
              // Now add this.state.divstyle in style property to access styles
              <div clasName="innerDiv" style={this.state.divstyle}></div>
           </div>
         )
        }
    }
    export default Someclass;