0

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;

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

When im trying to change the width value it throws me this error setState(…): takes an object of state variables to update or a function which returns an object of state variables Can you help me on this?
to change the width you have to follow same pattern this.setState({divstyle : { ...this.state.divstyle, width: 'X%'}})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.