Home > front end >  Conditional rendering for same component not triggering didmount in react
Conditional rendering for same component not triggering didmount in react

Time:06-23

{
  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.

CodePudding user response:

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"/>
 )
}

CodePudding user response:

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.

  • Related