0

I am trying to import a React component Menu.jsx from App.jsx in my Electron app. No errors are showing up, but nothing is being rendered and are not added to the DOM (the body is empty when I looked at the devtools). Not even the heading is being added.

Project Structure

App.jsx:

import * as React from "react";
import { createRoot } from "react-dom/client";

import Menu from "./components/Menu.jsx";

function App() {
  return (
    <>
      <h1 style={{ margin: "0 0 2rem 0" }}>Let's Start Training!</h1>
      <Menu />
    </>
  );
}

const root = createRoot(document.body);
root.render(<App />);

components/Menu.jsx:

export default function Menu() {
  return (
    <div className="vbox" style={{ width: "16rem" }}>
      <button>Times Table</button>
      <button>Addition</button>
      <button>Both</button>
    </div>
  );
}

When I put the Menu() component directly in App.jsx, everything is being rendered correctly. When I remove the line <Menu /> from App.jsx, at least the heading is being rendered.

1 Answer 1

-1

Your issue how Electron loads your components. The problem is caused by your createRoot(document.body) call.

In React 18+, you cannot mount a React root directly onto document.body. When you try to render <Menu />, React overwrites the entire <body> and removes all existing nodes, causing the DOM to end up empty.

This is why:

  • <h1> disappears when <Menu /> is added

  • nothing shows up in DevTools

  • no errors occur (React silently replaces <body>)

To fix the issue create a real root container

In your index.html (Electron preload page), add:

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

Then update App.jsx:

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(<App />);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. I tried that, but it didn't work initially. I got an error which said ReferenceError: React is not defined. Then I added this line to Menu.jsx, and it is now working perfectly: import * as React from "react"; Thanks 😊

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.