0
{
  toEmail.length ? (
    <TagInputHere
      initialValue={toEmail}
    />
  ) : (
    <TagInputHere
    />
  )
}

so in above code, the componentDidMount is not getting called when the condition is true, instead componentDidUpdate is getting called.

2 Answers2

0

Always use keys when you are using more than one instances of the same component in your JSX. Put keys to both of them so React can differentiate them.

Like this:

{
 toEmail.length ? (
  <TagInputHere
    key="1"
    initialValue={toEmail}
   />
 ) : (
  <TagInputHere key="2"/>
 )
}
Milos Pavlovic
  • 1,355
  • 1
  • 2
  • 7
  • When I wrap the second component in fragment, this seems to be working fine, what could bee the reason? – Kashyap Suthar Jun 23 '22 at 11:12
  • Not sure about that, maybe fragment is some kind of HOC so it will render and maintain all children isolated from outer JSX. Anyway you need keys, solution with fragment is just a workaround and not proper solution for your problem. – Milos Pavlovic Jun 23 '22 at 11:19
  • Also why both components will not work differently without the key? – Kashyap Suthar Jun 23 '22 at 11:21
  • Because one of the core principles React is relaying on, in order to be fast as much as possible, is to use keys when working with same component instances - key in this case is basically an identity for react element which will help React to isolate each instance and to dedicate state and lifecycle to each instance separately(to prevent mixing states and lfc methods as was the case within your problem). – Milos Pavlovic Jun 23 '22 at 11:32
  • About your react key problem, I found an answer that might satisfy you: https://stackoverflow.com/a/42801409/17334278 – Mike Le Jun 23 '22 at 11:32
0

In the first initialization of the parent element, <TagInputHere> has been appended to the DOM, when the other condition is true, the TagInputHere lifecycle will be didUpdated and no longer initialized. If you want to use the TagInputHere component independently, add a key attribute and pass a unique value to each of them.

Mike Le
  • 96
  • 3