Home > Back-end >  retuning conditional children not working
retuning conditional children not working

Time:10-20

my header:

<header className="app-header">
        {newChildren && <ModalLogin isModal={modalActive} closePop={closePop} children={newChildren} />}
        <HeaderPublic schema={HeaderPublicLinkSchema} />
      </header>

where I am setting newChildren for tempate.

on click of either login or register, I am trying to switch the children. but not works;

here is the function for click event.

const [modalActive, setModalActive] = useState(false);
  let newChildren: ReactElement | undefined = undefined;
  const openPop = (temp: string) => {
    console.log('temp', temp);
    if (temp === 'register') {
      newChildren = <FormRegister closePop={closePop} registerSubmit={onRegisterSubmit} />;
    }
    if (temp === 'login') {
      newChildren = newChildren = <FormLogin />;
    }
    setModalActive(true);
  };

Not able to understand the issue. any one help me please?

CodePudding user response:

Ok so openPop gets called, sets a local variable newChildren to some components, and calls a state setter setModalActive which will immediately trigger a re-render.

Once it re-renders, your let newChildren is undefined. I think this is a classic mistake trying to use let vars mutation like vanilla JS as a way to store state, and have some click/etc handler modify it. You can't do that in a function component because they are "pure" -- called per render, no local state stored, except for the useState, useRef etc return values.

If you have data that you want to persist between renders, use additional state. You can't use let and hope those values persist via changing them via a click handler.

More concretely, whenever you are tempted to use let x, use state:

const [newChildren, setNewChildren] = useState()

The only time let x and conditional reassignment to it will persist through output is if that assignment is made during render and not during an event.

Basically, think of any time you call setState as calling your function anew and all of the implications of that.

  • Related