solidjs/templates

Check if root element is present instead of unsafe casting to HTMLElement

aminnairi opened this issue · 1 comments

It would be great to warn the user in the console if the root element is not present with a friendly message.

For now, the error that a user might have whenever the root element is not found (missing div, wrong id, mispelled, ...) is the following.

Uncaught TypeError: Cannot read properties of null (reading 'firstChild')

Which is not the friendliest error message in the world, and I understand if this is something that can and should be userland.

Instead, what I would suggest would be to add some more code in the index.tsx file in order to check for whether the element is indeed present or not.

/* @refresh reload */
import { render } from "solid-js/web"

import "./index.css"
import Main from "./main"

const rootElement = document.getElementById("root")

if (!(rootElement instanceof HTMLDivElement)) {
  throw new Error("Root element not found. Did you forget to add it to your index.html? Or maybe the id attribute got mispelled?")
}

render(
  () => <Main />,
  rootElement
)

This has three benefits:

  • It prevents forcing the type of something that might be either null or an HTMLElement as an HTMLElement
  • It helps prevent spending too much time decyphering the error above and creates a better user experience for initializing the app
  • At the point of the render call, the rootElement has its type infered as HTMLElement automatically since it is not possible in this branch to be null (because of the throw that stops the execution of the process) so it does not need extra type casting

It would be nice to have it in the templates to enhance the user experience since this is not something that will add too much overhead at runtime (since it is run once per page load) and can be nice for spotting silly mistakes.

Hey! Thanks for filling out the issue.

That is a nice idea. I'll refactor the templates to add a message if the root isn't found only in dev :)