Just trying to create my first React module and test a simple ‘Hello World’.
I’ve simply created a new page called “React Test” and added a custom HTML block with a <div id=”app”></div> container. I’m using Sage9 style routing to load a script for this new page:
import { createRoot } from "@wordpress/element";
import Test from "../react/test.js";
export default {
init() {
console.log('hello from react test');
const domNode = document.getElementById("app");
console.log(domNode);
const root = createRoot(domNode);
root.render(<Test />);
},
finalize() {
}
}
This is my React module test.js -
import { useState} from '@wordpress/element';
function Test() {
return (
<>
<p>Hello World</p>
</>
);
}
export default Test;
But I am getting the following error:
12:42:14 PM [vite] (client) Pre-transform error: Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
Plugin: vite:import-analysis
File: /Users/kevinpriceward/Sites/mtswheelsolutions/public_html/app/themes/mtswheelsolutions/resources/js/react/test.js:5:25
3 | return (
4 | <>
5 | <p>Hello World</p>
| ^
6 | </>
7 | );
So I tried saving test.js as test.jsx and whilst error no longer shows, the module doesn’t load at all and I don’t get the console log “hello from react test” - what am I doing wrong?