skip to Main Content

My react app has a toggle button called Technical. If it is toggled on, we display , a custom component that offers a collection of highly technical options for the user. It has a lot of state. I am having this problem: when the user toggles the Technical button off, the stored state vanishes, and when the button is toggled back on, we are returned to the default state.

How can I preserve that state while making the FilterGroup (and the screen real estate it takes up) temporarily vanish?

Already tried:

  1. Wrapping this entire item in <> </>
  2. Wrapping FilterGroup in <> </>

Here’s the relevant code:

{technical ? <FilterGroup ref={(fg) => theFilterGroup = fg} /> : null}

2

Answers


  1. Chosen as BEST ANSWER

    Thank you, Unmitigated, for half the answer. Here's what else I had to do. This is an excerpt from my FilterGroup render function, as corrected.

            {range.map((r, i) => (
              <div className="box">
                <div className="rc-slider" key={i}>
                  <label className="common-label">{r.name}</label>
                  <Range
                    min={r.min}
                    max={r.max}
                    defaultValue={[this.state[r.from], this.state[r.to]]}
                    handle={this.handle}
                    tipFormatter={(value) => `${value}`}
                    onChange={(e) => this.rangeChange(e, r.from, r.to)}
                  />
                </div>
              </div>
            ))}
    

    By way of explanation, r.from and r.to (fields of each Range object in the range array) are strings which are field names in this.state. r.min and r.max are numbers. Previously the defaultValue line read:

                    defaultValue={[r.min, r.max]}
    

    and this default value was being reimposed every time the FilterGroup reappeared after having disappeared.


  2. You can pass a prop to FilterGroup to indicate whether or not to show it.

    <FilterGroup show={technical} ref={(fg) => theFilterGroup = fg} />
    
    const FilterGroup = forwardRef({show}, ref) {
        // hooks here...
        if (!show) return null;
        // return actual content...
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search