简体   繁体   中英

Can I include a single React component in a non-React environment via Javascript?

What I'd like to achieve is the ability to dynamically add single react components to a vanilla (or any other project) via Javascript.

Essentially a web component, without the compatibility woes.

For example: I create a component in React, build the project and it makes a bundle. Let's say I call the bundle "mycomponent.js"

Is there a way to then include that file in an unrelated project, either in an HTML script tag or bundler, then add it to the DOM dynamically with:

const elRef = new myCustomElement() //or some other syntax
elRef.customEvent = (data) => { console.log(data) }
document.body.appendChild(elRef)

Yes you can, you just need to set a mounting node for react to render your components. Something like:

<div>
  <!-- rest of your page -->
  <div id="root"></div>
  <!-- rest of your page -->
</div>

//Somewhere in your JS
React.render(<YourComponent />, document.getElementById("root"));

React won't change anything outside of its mounting DOM node, so you can have a full page and render only some widget with react if you want to. You don't need to render the entire page with react

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM