'How to pass variable such as object, string or array in html attribute to react app

I am trying to pass data to react component from html. It works when you pass a string statically added. I would like to pass a dynamic data from a variable. Here is what I am trying.. Oh I am trying to build an embeddable widget with react.

<script>
  let d1 = '{"name":"widget1","counter": 1}'
  let d2 = '{"name":"widget2","counter": 10}'
</script>

<div  data-setting={d1} class="widget-1" ></div>
<div  data-setting={d2} class="widget-1" ></div>

Here d1 or d2 just goes as a string it doesn't replace the variable defined above.

The code is then executed to index.js like this

const widgetDivs = document.querySelectorAll('.widget-1');


widgetDivs.forEach(div => {
  ReactDOM.render(
      <React.StrictMode>
    <App setting={div.dataset.setting}/>
  </React.StrictMode>,
    div
  );
});

So how can I pass dynamic data from variable from the html code in data attribute? or there are any better approach to do this? Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source