I've trying to integrate react into an existing project. I'm starting by setting up a simple button component to get started. The project is an express app that uses handlebarsjs to handle the views.
I have created the jsx file with correct syntax and successfully compiled to an output file. I am then importing that output file into my main.js script which is requested by the main layout view.
I can see the successful compilation by babel in the dist directory. I don't have any errors in the browser console. however, for some reason the component is not rendered on the page.
What could I be overlooking?
main-layout.hbs
<script type="text/javascript" src="/js/main.js"></script>
main.js
import submitHandler from './form.js';
import button from './components/button.js';
import lottieInit from './animations/lottie-handler.js';
import ReactButton from '../../dist/bca-react-component-library/button.js';
import { createRoot } from 'react-dom/client';
function loadButton() {
const root = createRoot(document.getElementById('react-app'));
root.render(
<ReactButton />
);
console.log('rendered ReactButton');
}
window.addEventListener("load", runAllFunctions);
function runAllFunctions() {
submitHandler();
lottieInit();
button();
loadButton();
}
button.js (compiled)
export default function ReactButton() {
return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("button", null, "click here"));
}
button.js (pre-compile)
export default function ReactButton() {
return (
<>
<button>click here</button>
</>
);
}
babel.config.json
// .babelrc or babel.config.json
{
"presets": ["@babel/preset-react"]
}
Edit: this is solve. As noted by @mukilan Palanichamy below, I needed to call the react library in my html.
Also in my case I needed to change the location I was storing my button component file at, to a directory that my express app was configured to serve web assets from. In this case under /public/.