javascript - React based SPA WP-Theme react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__ is undefined - Stack Overflow

admin2025-04-26  4

I'm trying to create a custom react-based WP-Theme for a SPA.

Versions: Wordpress: 6.7.1. React: 18.0.0 Npm: 10.8.2 Node: 18.20.5

The functions.php file of my Wordpress installations contains the "render-react"-Div, to which I want to render my react components.

<?php
function my_react_theme_scripts() {
    wp_enqueue_script('my-react-theme-app', get_template_directory_uri() . '/build/index.js', array('wp-element'), '1.0.0', true);
}

add_action('wp_enqueue_scripts', 'my_react_theme_scripts');
?>

<div id="render-react"></div>

I can get the div via the query-selector and I can create the root. However, when I try to render anything to it I get an error.

import "./styles/main.scss"
import React from "react"
import ReactDOM from "react-dom/client"


// Render the React Component
console.log("test1");
var rootElement = document.querySelector("#render-react");
console.log(rootElement);
const root = ReactDOM.createRoot(rootElement);
root.render(<h1>Hello, world</h1>); // <- The error occurs here.

I'm not sure, if this problem is reproduceable, but I've tried reading docs again and a again, I've tried installing different react versions, looking around in forums and playing around with my code but nothing helps. Any ideas?

转载请注明原文地址:http://anycun.com/QandA/1745599765a91005.html