Jeff
Jeff

Reputation: 8421

Redux: render compoent based on a condition

In my react-redux application, i have the following react component:

render(){

      return(<div style={this.setStyler()} >
                  {this.props.value}
            </div>);
  }

The setStyler() manipulate a reducer and return a value which should be applied as css.

The problem is, i face with the error:

Cannot update during an existing state transition (such as within  render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

It seems that redux does not allow me to render component based on state condition. but i don't know how can i fix this issue?

Update:

setStyler(){
    if(this.props.activeWord!=this.props.wordId)
      return { color:'black', fontWeight: 'normal' };
    if(this.props.letterId>this.props.activeLetter && this.props.activeWord==this.props.wordId)
         return { color:'black', fontWeight: 'normal' };

    if(this.props.letterId==this.props.activeLetter && this.props.activeWord==this.props.wordId){
          if(this.props.value==this.props.newTypedLetter){
               this.props.color({ color:'green', fontWeight: 'bold' });  //change  reducer
               return { color:'green', fontWeight: 'bold' };
          }
          if(this.props.value!=this.props.newTypedLetter){
               this.props.color({ color:'red', fontWeight: 'bold' });     ////change  reducer
                return { color:'red', fontWeight: 'bold' };  
               }

    }
    if(this.props.letterId<this.props.activeLetter && this.props.activeWord==this.props.wordId)
            return this.props.letterColor;

  }

Upvotes: 0

Views: 231

Answers (1)

Dmitrijs Balcers
Dmitrijs Balcers

Reputation: 157

I would say that in this case you should try to call this.setStyler() from constructor and from componentWillUpdate. And then you simply should read the value from redux store from your render function.

This should do the job, but still is not the best approach IMO, due to you are making your component fat. You can try to read this post about Presentational and Container Components which will explain a pattern of designing your components.

The problem is that, you are trying to modify something from render function, Which is a side effect. This in Functional Programming paradigm, which react tries to follow, is an anti-pattern. And as you can see react tries to tell you exactly that through the error you received.

Upvotes: 1

Related Questions