Ir al contenido principal

How to create an AEM component using Reactjs

In this tutorial, I will show how to use use Adobe's archetype to create an AEM application with React.js support and also how to add a new React.js component so that it can be added into a page, above is the vid and below you will find some useful notes. In the second part we will see how to configure the Sling Model for the AEM React component.
  1. 1.

    Pre-reqs

  2. 2.

    Creating an AEM application with React.js support

    • You will need Adobe's archetype for creating your AEM application with SPA support. The support was added starting from the 23rd version of the archetype.
    • If the 23rd version is not out yet you will have to clone and compile the archetype locally to be able to use it
      git clone https://github.com/adobe/aem-project-archetype.git
      
      Change into the new directory and build the archetype
      cd aem-project-archetype
      mvn clean install
      
    • So let’s create the app from scratch. I am providing the most important properties in a single line here given that the other properties will be inferred from them, notice that the version that I am using is the 23-SNAPSHOT and that optionFrontendModule was set to react
      mvn archetype:generate  "-DarchetypeGroupId=com.adobe.granite.archetypes"  "-DarchetypeArtifactId=aem-project-archetype"  "-DarchetypeVersion=23-SNAPSHOT" "-DoptionFrontendModule=react" "-DoptionAemVersion=6.5.0" "-DgroupId=co.dlighthouse.aem.reactsimpleexample" "-DappsFolderName=react-simple-example" "-DartifactId=aem-react-simple-example"
      
    • Let’s build and deploy our new app (make sure that you have AEM up and running)
      mvn clean install -PautoInstallPackage -Padobe-public
      
  3. 3.

    AEM component using reactjs

    • For creating an AEM component using react we need at least 4 things, a skeleton AEM component with a dialog, a react component, an entry importing the component inside the import-components.js file and a sling model which I’ll be configuring in the next video.
    • I am going to use the yeoman generator for creating the skeleton AEM component for me with some additional example fields in the dialog. I am calling it basic-component and I am making sure that the names for the folders and component group match my current application’s configuration.
      yo aem-application:aem-component mavenAppsModuleName=ui.apps componentParentPath=react-simple-example/components componentNodeName=basic-component componentName="Basic Component" componentGroup="react-simple-example - Content" mavenBundleModuleName=core javaRootPackageName=co.dlighthouse.aem.reactsimpleexample.core javaModelRelativePackageName=models javaModelClassName=BasicModel
      
    • We should end up with a component inside react-simple-example/components called Basic Component, if you check the dialog’s xml file you will find two example fields, one for the text and another for the checkbox.
      <items
        jcr:primaryType=\"nt:unstructured\">
          <text
              jcr:primaryType=\"nt:unstructured\"
              sling:resourceType=\"granite/ui/components/coral/foundation/form/textfield\"
              fieldLabel=\"Text\"
              name=\"./text\"/>
          <checkbox
              jcr:primaryType=\"nt:unstructured\"
              sling:resourceType=\"granite/ui/components/coral/foundation/form/checkbox\"
              text=\"Checkbox\"
              uncheckedValue=\"false\"
              value=\"true\"
              name=\"./checkbox\"/>
          <checkboxType
              jcr:primaryType=\"nt:unstructured\"
              sling:resourceType=\"granite/ui/components/foundation/form/hidden\"
              name=\"./checkbox@TypeHint\"
              value=\"Boolean\"/>
      </items>
      
    • Inside the ui.frontend module you will find the React.js components inside the src/components folder. Create a new folder inside it, call it BasicComponent and also create an index.js file. Add the imports for the reactjs library and mapTo helper from adobe
      //Imports
      import React, { Component } from 'react';
      import { MapTo } from '@adobe/cq-react-editable-components';
      
    • Create an editconfig obj which will be used for displaying some text when the component is empty, in this case given that the component’s properties like the ones defined on the dialog are available through the react’s props object we can just check if props.text doesn’t have a value so that we can mark this component as empty
      const BasicComponentEditConfig = {
        emptyLabel: 'Basic Component',
      
        isEmpty: function(props) {
          return !props || !props.text;
        }
      };
      
    • Then we have the component which looks like a typical react component with its render method. Here we can output the values for the text and checkbox properties inside the props object
      class BasicComponent extends Component {
        render() {
          return (
            <div>
              My Text Property Value: {this.props.text},
              and checkbox: {this.props.checkbox ? 'checked' : 'unchecked'}
            </div>
          );
        }
      }
      
    • Finally we call mapTo helper function that maps the react component to a particular resourceType inside AEM so that aem knows which react component to use when rendering our page
      export default MapTo('react-simple-example/components/basic-component')(
        BasicComponent,
        BasicComponentEditConfig
      );
      
    • Then inside the import-components.js file we import the basic component
      import './BasicComponent';
      
    • Build and deploy the application again
      mvn clean install -PautoInstallPackage -Padobe-public
      
  4. 4.

Comentarios

  1. Hi Manuel,

    I am getting these errors while running the yo command...

    internal/modules/cjs/loader.js:582
    throw err;
    ^

    Error: Cannot find module '../../utilities/utilities'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
    at Function.Module._load (internal/modules/cjs/loader.js:506:25)
    at Module.require (internal/modules/cjs/loader.js:636:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at Object. (/usr/local/lib/node_modules/generator-aem-application/generators/aem-component/index.js:9:19)
    at Module._compile (internal/modules/cjs/loader.js:688:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)
    at Module.load (internal/modules/cjs/loader.js:598:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:537:12)
    at Function.Module._load (internal/modules/cjs/loader.js:529:3)

    Any idea why this could be?

    Cheers,
    Esai

    ResponderEliminar
    Respuestas
    1. Hey Esai, you are absolutely right :( given that I always test on a machine that has the yeoman generator I never encountered the problem, I am fixing the issue today, sorry for that! :(

      Eliminar
  2. Hi Manuel - I am getting an error when I run the final 'mvn clean install -PautoInstallPackage -Padobe-public' command:

    Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.7.6:npm (npm run build) on project mysite.ui.frontend: Failed to run task: 'npm run build' failed. org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1) ->

    Do you have any clues as to why I am getting this? I've tried using different versions of node and npm in the root pom.xml file, but I am still getting the error. Any advice would be greatly appreciated.

    ResponderEliminar

Publicar un comentario

Entradas populares de este blog

How to copy files from and to a running Docker container

Sometimes you want to copy files to or from a container that doesn’t have a volume previously created, in this quick tips episode, you will learn how. Above is the vid and below you will find some useful notes. 1. Pre-reqs Have Docker installed 2. Start a Docker container For this video I will be using a Jenkins image as an example, so let’s first download it by using docker pull docker pull jenkins/jenkins:lts

House price prediction 3/4: What is One Hot Encoding

A series about creating a model using Python and Tensorflow and then importing the model and making predictions using Javascript in a Vue.js application, above is the vid and below you will find some useful notes. Here, in part 3 of this series, I will show what is and how does one hot encoding works. In the first post, called House price prediction 1/4: Using Keras/Tensorflow and python , I talked about how to create a model in python, pre-process a dataset I've already created, train a model, post-process, predict, and finally about creating different files for sharing some information about the data for use on the second part. Then in part 2, called House price prediction 2/4: Using Tensorflow.js, Vue.js and Javascript , I took the model, the data for pre and post processing and after loading everything we were finally able to predict