Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

retuning conditional children not working

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading