How to use a shared react widget components in other react portlets - Liferay 7.4

203 views Asked by At

I have a requirement where I need to create reusable components in React and use them in other react portlets in Liferay.

Here are the steps I tried:

I have a react widget (reusable widget) and react portlet (consuming portlet)

  1. reusable widget:

    ReusableComponent.js

    import React from 'react';
    
    const ReusableComponent = () => {
      return <div>This is a reusable React component.</div>;
    };
    
    export default ReusableComponent;
    
  2. Import the component in other Portlets like:

    Portlet1.js

    import React from 'react';
    import ReusableComponent from '../../reusable-component/src/main/resources/jsx/ReusableComponent';
    
    const Portlet1 = () => {
      return (
        <div>
          <h2>Portlet 1</h2>
          <ReusableComponent />
        </div>
      );
    };
    
    export default Portlet1;
    
  3. Here is my .babelrc

    {
      "presets": ["@babel/preset-env", "@babel/preset-react"],
      "plugins": ["@babel/plugin-proposal-class-properties"]
    }
    

After I deployed I'm getting errors like: "Uncaught ReferenceError: Exports is not defined" and then "Liferay-am-loader . A require call has failed in loader.js", missing dependencies.

Am I doing anything wrong here? Can someone suggest to me how to implement the same?

1

There are 1 answers

0
Romeo Sheshi On

in the project of portlet1.js you should have an file .npmbundlerrc if not just create it and the import of the widget project

{
    
    "config": {
        "imports": {
            "reusable-component": {         
                "reusable-component": "^1.0.0"          
            }           
        }
    }
}

after you have instert the import you can call the import like this way

import ReusableComponent from 'reusable-component/jsx/ReusableComponent';

You can do the same think with liferay components or dipendencies just adding the import like this way in the example below the react and react-dom so to have same version as liferay

   {
        "config": {
            "imports": {
                "reusable-component": {         
                    "reusable-component": "^1.0.0"          
                },
                "@liferay/frontend-js-react-web": {             
                    "react": "*",
                    "react-dom": "*"
                } 
            }
        }
    }