Blending Best of Both Worlds: React JS into Salesforce Lightning Web Components (LWC)

Integrating React within a Salesforce Lightning Web Component (LWC) is a unique approach since LWC and React are both frameworks designed to control the DOM in their ways. However, it is possible to use them together, though it requires careful handling to ensure both libraries can coexist without issues.

React JS within LWC

Step 1: Setting Up Your Salesforce DX Environment

  1. Install Salesforce CLI: Make sure you have the Salesforce CLI installed on your computer. This is essential for creating and managing your Salesforce development projects.
  2. Create a New Salesforce DX Project: Open your terminal and run the command sfdx force:project:create -n myLwcReactProject to create a new project.
  3. Navigate into Your Project: Use cd myLwcReactProject to move into your project directory.
  4. Authorize a Dev Hub: If you haven’t already, authorize a Salesforce Dev Hub by running sfdx auth:web:login -d -a DevHub.
  5. Create a Scratch Org: Create a new scratch org with sfdx force:org:create -s -f config/project-scratch-def.json -a LwcReactOrg.
  6. Open the Scratch Org: To access your newly created org, use sfdx force:org:open.

 Install the lwc-react package. You can do this by running the following command in your terminal:

npm install lwc-react

Step 2: Import React to Your Salesforce Project

  1. Navigate to the LWC Directory: Within your project, navigate to force-app/main/default/lwc.
  2. Create a React App: You cannot directly create a React app here. Instead, you’ll integrate React manually. Download React and ReactDOM from a CDN or NPM and include them in your Salesforce static resources.
  3. Static Resource for React: Create a static resource for both React and ReactDOM. Use Salesforce Setup to upload these files as static resources.

Step 3: Creating Your LWC Component

  1. Generate LWC Component: Use sfdx force:lightning:component:create --type lwc -n myReactComponent -d force-app/main/default/lwc.
  2. Edit Your Component: In your myReactComponent directory, you’ll find three files: myReactComponent.js, myReactComponent.html, and myReactComponent.css. You’ll primarily work with the JS and HTML files.

Step 4: Integrating React into Your LWC

  1. Load React and ReactDOM: In myReactComponent.js, use loadScript from lightning/platformResourceLoader to load React and ReactDOM from the static resources you uploaded.
  2. Use React in Your Component: After loading React and ReactDOM, you can use them within the renderedCallback lifecycle method to render React components inside your LWC.
  3. Update Your HTML Template: Add a container in your myReactComponent.html where the React component will be mounted.

There is React Library published by Salesforce which can be used seamlessly within LWC

https://react.lightningdesignsystem.com/

import { LightningElement, track } from 'lwc';
import { loadScript } from 'lightning/platformResourceLoader';
import REACT from '@salesforce/resourceUrl/react';
import REACTDOM from '@salesforce/resourceUrl/reactdom';

export default class MyReactComponent extends LightningElement {
    reactInitialized = false;

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

        Promise.all([
            loadScript(this, REACT + '/react.production.min.js'),
            loadScript(this, REACTDOM + '/react-dom.production.min.js')
        ])
        .then(() => this.initializeReactComponent())
        .catch(error => console.error(error));
    }

    initializeReactComponent() {
        ReactDOM.render(
            React.createElement('div', null, 'Hello from React!'),
            this.template.querySelector('.reactContainer')
        );
    }
}

Add a container in your myReactComponent.html where the React component will be mounted

<template>
    <div class="reactContainer"></div>
</template>

Considerations

  • Performance: Embedding React inside an LWC can impact performance because of the overhead of loading React and managing two frameworks.
  • Framework Conflicts: Be mindful of potential conflicts between React’s and LWC’s handling of the DOM.
  • Maintenance: This approach requires careful maintenance, as updates to either framework can necessitate changes to your integration.

For more details

https://twirltech.in/architect-blogs/

Leave a Reply

Your email address will not be published. Required fields are marked *