AntiPattern Prop To State in some Prime React components => problems using redux form with Chips and others components

UI Components for React
Post Reply
rodriguezc
Posts: 5
Joined: 03 Jul 2012, 11:28
Location: Switzerland

19 Jun 2018, 15:52

It seems that mapping in constructor props to state is an anti pattern because if some high level component update props, the component is not updated.

For example the Chips components only update state from props in constructor:
https://github.com/primefaces/primereac ... s/Chips.js

Code: Select all

 constructor(props) {
        super(props);
        this.state = {values : props.value, focus: false}; //HERE IS THE PROBLEM
        this.inputFocus = this.inputFocus.bind(this);
    }
If redux form manages the Chips component, redux-form will change only the "value property" of Chips component.
I had the case with the "reset" function of redux form:

Code: Select all

<Chips value={field_managed_by_redux} />
Updated to
<Chips value={field_managed_by_redux_initial_value} />
Because this change is not detected by the Chips component, his state is not updated and the component is in a dirty state (props.value != state.values)

Perhaps you don't have the choice and you need to manage a state because of the complexity of react components.

I found a solution for this problem by adding the "componentDidUpdate" method in the Chips Component

Code: Select all

class WorkaroundChips extends Chips {
  componentDidUpdate(prevProps, prevState, snapshot) {
    if(this.state.values.length !== this.props.value.length) {     
      this.setState({ values:this.props.value});
    }    
  }
}
I think that if you use "props to state" pattern, it's a must to declare componentDidUpdate in order to avoid problems with libraries like redux form.

Sources:
https://www.reddit.com/r/javascript/com ... n_reactjs/

Post Reply

Return to “PrimeReact”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 19 guests