V
V
vzphvckm2020-01-06 21:55:59
JavaScript
vzphvckm, 2020-01-06 21:55:59

How to get rid of the memory effect in React?

Let's say a wizard component (i.e. a stepwise form) has a "step" state that determines which step of the form is currently being shown. Further:

switch (this.state.step) {
  case "first":
    return <input type="text" name="a" class="form-control" />;
  case "second":
    return <input type="text" name="b" class="form-control" />
}

Everything seems to be working fine, but if validation errors occur at the first stage of the form (we add the is-invalid class to the input), then this class also passes to the second new input at another stage, although this should not be due to rerendering. How to avoid it? Or clean everything manually?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2020-01-07
@vzphvckm

Add keys .
Yes, the documentation talks about keys in connection with lists, but in reality their scope is wider. If you want an element to be re-created in cases like yours, you must assign different keys to elements that are created in different branches of a switch, conditional statement, and so on. For example: there are no keys - there are keys .
But in general, it will be correct to assign classes depending on the value of some property in the state. Then there will be no such problems, the keys will not be needed.

D
Dmitry Sviridov, 2020-01-06
@dimuska139

I highly recommend not to cut your form processing algorithms, but to use ready-made proven solutions like react-final-form or formik . This will greatly simplify your life and save you from tons of crutches and bicycles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question