Skip to content

preload.ts can't see root element when implementing React #220

@kyleatcolenso

Description

@kyleatcolenso

React won't latch onto the document as it can't find the root we're giving createRoot. Here's my implementation built off the Webpack + Typescript template.


index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World!</title>

  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

src/App.tsx

import { createRoot } from 'react-dom/client';

console.log(document); // #document object
console.log(document.body); // null
console.log(document.getElementById('root')); // null

const root = createRoot(document.getElementById("root"));
root.render(<h2>Hello from React!</h2>);

preload.ts

import './App';

tsconfig.json

{
  "compilerOptions": {
     ...
    "jsx": "react-jsx",
     ...
    "paths": {
      "*": ["node_modules/*"]
    }
  },
  "include": ["src/**/*"]
}

Problems

  • When running npm start, I am presented with these errors
Image

Note that the first three console.logs coincide with the logs from src/App.tsx.

React version: 18.3.1
Node version: 20.10.0
Yarn version: 1.22.22

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions