Charith H
Charith H

Reputation: 355

How to pass parameters from root html element to ReactJS from Ruby on Rails app

I am trying to implement ReactJS on a Ruby on Rails application using webpacker gem.

Does anyone know how to read/pass data attributes to ReactJS component.

Please find the code below.
in index.html.erb
<div id="data" data-item-id="<%= @item.id %>"></div>

in Data.jsx file

<!-- language: lang-js -->

class Data extends React.Component {
  constructor(props) {
    super(props);
  }

 componentDidMount() {
   this.getSiteDetails();
 }

 getSiteDetails(){
  fetch(i want to pass data attributes here along with the url)
 }

 render() {}
}

ReactDOM.render(<Data />, document.getElementById('data'));

Upvotes: 0

Views: 412

Answers (1)

Giang Le
Giang Le

Reputation: 7044

You can do this:

 getSiteDetails(){
   const itemId = document.getElementById('data').dataset.itemId
   fetch(you can use itemId in here)
 }

Upvotes: 1

Related Questions