[SalesForce] Uncaught (in promise) TypeError: c.createElement is not a function

I am getting the below error when using react js in LWC. Any idea how to resolve this.

Uncaught (in promise) TypeError: c.createElement is not a function

LWC

import {
    LightningElement
} from 'lwc';
import {
    loadScript
} from 'lightning/platformResourceLoader';
//add as static resource
import React from '@salesforce/resourceUrl/react';
import ReactDOM from '@salesforce/resourceUrl/reactdom';

export default class Reactjslwc extends LightningElement {
    async connectedCallback() {
        //load react & react-dom
        Promise.all([
            loadScript(this, React),
            loadScript(this, ReactDOM),
        ]).then(() => {

            ReactDOM.render(React.createElement('div', null, 'Hello React'), this.template.querySelector('div'));
        });
    }

    disconnectedCallback() {
        ReactDOM.unmountComponentAtNode(this);
    }
}

HTML

<template>
    <p>ReactJS</p>
</template>

Best Answer

I am not sure why you want the React to work inside lightning web component.If you have a single page app built in React and want to render in salesforce the best bet would be to use the lightning:container.

Most of the functionality that React components framework provide , lightning web components also provide them.

However still for some reason if you still want to render React in lwc , I was able to get it working .

1.For some reason React-DOM import failed when i used the UMD version in dev mode for React . I had to directly upload the minified version instead .

2.Note that when you use the third party lib ,you have to use lwc:manual directive to allow DOM manipulation

3.When you upload the third party lib ,the function of third party is added to window object.

Here is the working code

<template>
<div class="c-container">
    <p>ReactJS POC Component</p>
    <div lwc:dom="manual" class="reactcontainer"></div>
</div>

The Js code

import { LightningElement } from "lwc";
import { loadScript } from "lightning/platformResourceLoader";
import React from "@salesforce/resourceUrl/reactlib";
import ReactDOM from "@salesforce/resourceUrl/reactdom";

export default class ReactCmp extends LightningElement {

 reactlibInitialized = false;

 renderedCallback() {
    if (this.reactlibInitialized) {
        return;
    }
    this.reactlibInitialized = true;

    Promise.all([loadScript(this, React), loadScript(this, ReactDOM)])
        .then(() => {
            window.ReactDOM.render(
                window.React.createElement("div", {}, "Hello React"),
                this.template.querySelector("div.reactcontainer")
            );
        })
        .catch(error => {
            // eslint-disable-next-line no-console
            console.log(error);
        });
   }

   disconnectedCallback() {
     window.ReactDOM.unmountComponentAtNode(this);
  }
}
Related Topic