Redux+React Manage State Of Two (or More) Same Elements. How?

- 1 answer

Hello everyone) I can't understand how to manage state (open/closed) for two absolutely same elements (for example, datepicker- "start date" and "end date"). Now i made two action CHANGE_STATE1 and CHANGE_STATE2, but when i look at this code i'm going to frustration. And some examples for better understanding: First popover and it's state:

<Popover open={this.props.isOpenPopoverLeft}>

And second popover:

<Popover open={this.props.isOpenPopoverRight}>

As you can see, elements absolutely identical, but has different state. How to right beautiful code for that?



I had this exact case (start and end pickers), and addressed it with an edge argument, referring to two constants, START and END.

Your action creator looks like:

setDate(edge, date)

Your React class might have a method like:

_onSelectDate(edge, date) {
  dispatch(setDate(edge, date));

and you can bind in the render method like

render() {
    // holds the state in an object like { start: true, end: false }
    const popoverState = this.props.popoverState;

    return (

        <Popover open={ popoverState[START] }>
              onChange={ this._onSelectDate.bind(this, START) }/>

        <Popover open={ popoverState[END] }>
              onChange={ this._onSelectDate.bind(this, END) }/>



Depending on how similar the layouts are, you could also map over an array like [START, END], or have a new component that takes edge as a prop.