How to Fix ‘Uncaught TypeError: e is null’ in AlpineJS

Here’s a quick piece of troubleshooting info for anyone using AlpineJS.

AlpineJS is “a rugged, minimal framework for composing JavaScript behavior in your markup … Alpine.js offers you the reactive and declarative nature of big frameworks like Vue or React at a much lower cost”.

I was doing some very simple work with the x-if directive today and kept running into an annoying error message in the develop console.

Problem Code

See the Pen AlpineJS Example (Broken) by Stephen DeLorme (@StephenDeLorme) on CodePen.

Uncaught TypeError: e is null
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7
    alpine v2.x.x/dist/alpine.min.js:7

No matter what I tried to do to simplify things and strip out code to see what was causing the error message, I couldn’t find anything repeatable.

Just to be sure, I checked the documentation on x-if. Sure enough, there was my answer:

Note: x-if must have a single element root inside the <template></template> tag.

Adding a single HTML element inside the <template> tag fixed my issue and made the console error go away.

Lesson learned: RTFM. =)

Corrected Code

See the Pen AlpineJS Example (Fixed) by Stephen DeLorme (@StephenDeLorme) on CodePen.