Using conditional rendering throws a console error of "Cannot read properties of null (reading 'insertBefore')"

I am trying to display a textbox when the result of a v-if has one value, and a dropdownlist when it has another, but this is blowing up.

I have replicated it here with a very simple sandbox:

https://codesandbox.io/p/sandbox/vue-directives-conditional-rendering-v-if-v-else-v-show-v-for-forked-pk4qmw


1 Reply

YS Yohapuja Selvakumaran Syncfusion Team August 20, 2024 01:15 PM UTC

Hi Kevin Lane,


Thank you for reaching out to us with the issue you're experiencing. We understand that you're encountering a TypeError when swapping between components in your Vue application. The error seems to occur when the ejs-textbox component tries to interact with the DOM element that isn't fully rendered.


To resolve this issue, We recommend using the v-show directive instead of v-if for the conditional rendering of your components. The key difference between the two is that v-if completely removes the element from the DOM when the condition is false, while v-show only hides it. By using v-show, the element remains in the DOM, preventing the insertBefore error from occurring.


Here's how you can adjust your code:


 

<template>

  <div style="margin-top: 100px">

    <button @click="foo = !foo">Swap component</button>

    <div v-show="foo">

      Input box

      <ejs-textbox />

    </div>

    <div v-show>

      Dropdown

      <ejs-dropdownlist />

      <ejs-button>berly</ejs-button>

    </div>

  </div>

</template>

 

 



Sample:
https://codesandbox.io/p/sandbox/condition-rendering-issue-forked-6z238y?file=%2Fsrc%2Fcomponents%2FFoo.vue%3A1%2C1-14%2C12&workspaceId=d0af9141-d359-4207-af4b-d4fd52a174b8



This adjustment should help prevent the error by ensuring that the components stay in the DOM even when they're not visible.


Please let me know if this solution works for you or if you need further assistance.



Regards,

Yohapuja


Loader.
Up arrow icon