Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
kyleatcolenso opened this issue Jan 22, 2025 · 1 comment
Closed

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

kyleatcolenso opened this issue Jan 22, 2025 · 1 comment

Comments

@kyleatcolenso
Copy link

kyleatcolenso commented Jan 22, 2025

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

@kyleatcolenso
Copy link
Author

For those looking for a solve, wait for the DOM content to load

import { createRoot } from "react-dom/client";
import Layout from "./components/Layout/Layout";

document.addEventListener("DOMContentLoaded", () => {
  const root = createRoot(document.getElementById("root"));
  root.render(<Layout />);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant