HubSpot / cms-react-boilerplate

Other
70 stars 33 forks source link

Document how module data is obtained #43

Open kaifresh opened 2 years ago

kaifresh commented 2 years ago

Hey guys,

I'm curious to understand how you're extracting module data from the DOM and getting it into the module itself. It seems like it occurs on this line, but I haven't been able to find any documentation on exactly what is going on here. Could you guys please update the read me or add a wiki page to explain this? Thank you!!!!

dholland commented 2 years ago

Hey @kaifresh -

Here is my take:

In the module.html file, there is a script tag where it is converting the module data into JSON.

 <script
    type="application/json"
    data-module-instance="{{ instance_id }}"
    data-portal-id="{{ portal_id }}"
  >
   {{ module|tojson }}
  </script>

When the javascript file runs is find this script tag and loads it into the targetModulesData variable

 const targetModulesData = document.querySelectorAll(
  '.cms-react-boilerplate > script[type="application/json"]',
);

datasets pull the different data-* items on the script tag

data-module-instance="{{ instance_id }}"
data-portal-id="{{ portal_id }}"

and textContent is the JSON within the script tag

these values are then passed into the react app as props. Parsing the JSON on the way into the app.

<App
    portalId={dataset.portalId}
    moduleData={JSON.parse(textContent)}
    moduleInstance={dataset.moduleInstance}
/>

In my recent case, I wanted to fetch HubDB rows and load them as props into the react app. So I created a new obj from both my hubDB rows and the module data and then send that as json into the script tag.


{% set rowsArray = [] %}
{% set moduleData = {'floorPlans': rowsArray, 'module': module } %} 

  {% for row in hubdb_table_rows(5416070) %}
    {% do rowsArray.append(row) %}
  {% endfor %}

<div class="cms-react-boilerplate">
  <script
    type="application/json"
    data-module-instance="{{ instance_id }}"
    data-portal-id="{{ portal_id }}"
  >
   {{ moduleData|tojson }}
  </script>

Hope that's helpful!