0

Is it possible to add a build index.html of a React app to a div in my HTML/ColdFusion website?

I built a chatbot in React using hooks. Bellow is my App.js which imports my ChatBot.js component.

import './App.css';
import MyChatBot from './ChatBot';

function App() {
  return (
    <div className="App">
      <MyChatBot/>
    </div>
  );
}

export default App;

It is working. I have a ColdFusion/HTML website where I would like to include this "chatbot" or the generated index.html from npm run build to a div

<!-- ColdFusion Website here --->
<div id="myChatBot"></div>

The idea is to have the React application inside that div. Is it possible?

Thank you.

myTest532 myTest532
  • 2,091
  • 3
  • 35
  • 78

2 Answers2

3

Yes, you can. You just need to pass the element ( where you want to mount the react app ) to ReactDOM.render method. Then bundle your react app using a bundler, say webpack, and include that bundle via script tag or via the current build process in your app's html.

HTML

<!-- Website Markup --->
<div id="myChatBot"></div>

<!-- Include React bundle --->
<script src="bundle.js"></script>

React

import ReactDOM from "react"
import App from "./App"

ReactDOM.render(<App/>, document.getElementById("myChatBot"))
Hemant Parashar
  • 3,684
  • 2
  • 16
  • 23
  • 1
    Do you have an example of how I could crate the ```bundle.js```? – myTest532 myTest532 Feb 18 '21 at 17:21
  • You can use webpack - https://webpack.js.org/ or parcel.If you're using `create-react-app` it already has the process setup - https://create-react-app.dev/docs/production-build – Hemant Parashar Feb 18 '21 at 17:28
  • Yes, I used ```create-react-app``` and I already build my application using ```npm run build```. It generates the index.html (not a bundle.js file). – myTest532 myTest532 Feb 18 '21 at 17:32
  • Sorry, I'm new to it. Is the ```build/static/js/main.c3b68fb6.chunk.js``` the bundle.js file? Also, should I add ```ReactDOM.render(, document.getElementById("myChatBot"))``` in my App.js instead of ```export default App;```? – myTest532 myTest532 Feb 18 '21 at 17:39
  • If you're using CRA then you might have to tweak the process. You can read it here https://stackoverflow.com/questions/59331493/combine-react-build-output-into-single-js-file – Hemant Parashar Feb 18 '21 at 18:17
  • Thank you. Th only issue is that I have to include all the .js and .css generated in the static folder. I wish it could generate or combined all in one file – myTest532 myTest532 Feb 18 '21 at 19:46
0

Hope this is helpful to you: https://reactjs.org/docs/add-react-to-a-website.html

Gist of it is you have import the React scripts and render it to that id:

const domContainer = document.getElementById('myChatBot');
ReactDOM.render(e(LikeButton), domContainer);
medzz123
  • 219
  • 2
  • 6