Dinesh Pallapa
Dinesh Pallapa

Reputation: 1212

React + Redux +Rails and webpack without gem

I am new to React I am trying to integrate react with rails without the gem. Somehow I succeed to integrate by using web pack. I am facing a small problem while retrieving data to views which was already stored in the database.

Here some brief explanation

def index
  @products = Product.all
end

With Rails, I can access to that instance variable and loop through that and display data in views

My idea is to assign instance variable to variable and using this React component as below.

products = @products

products.map(function(product){
    return(
      product.id
      product.name
    )
});

But It didn't work for me.

I hope someone already done it and had good idea about react and rails without using gem help me to find a solution for it

Thanks in advance

Upvotes: 1

Views: 519

Answers (2)

Hardik Upadhyay
Hardik Upadhyay

Reputation: 2659

I am also newbie to react so, as per my knowledge we can't assign rails object to react directly

I did this to my project for same functionality like you

var Body = React.createClass({
    getInitialState() {
        return { products: [] }
    },
    componentDidMount() {
        $.getJSON(`/products.json`, (response) => { this.setState({ products: response }) });
    },
})

After this you can use 'products' variable like this

this.state.products

For more reference visit this

Hope its help you.

Upvotes: 1

grizzthedj
grizzthedj

Reputation: 7505

You need to render JSON on the rails side, then consume it from React. You won't be able to access the @products variable outside of the rails app.

def index
  @products = Product.all
  render :json => @products.to_json
end

Upvotes: 1

Related Questions