changing props in react_component when using react_rails

499 views Asked by At

I am using this helper to display a datepicker component

      <%= react_component "MyDatePicker", startDate: '', endDate: ''%>

I want to pass javascript values to startDate and endDate props. Any possible way to do this?

2

There are 2 answers

1
Abhilash On BEST ANSWER

Fixed this by using Pubsub. What I did is publish the user selected values in the javascript first. Then on react parent component lifecycle method subscribed to the previously published event and use setState to change the state based on that.

Now am on mobile but i will publish the code for clarity once i got access to a pc.

update

Using pubsub is easy. First we need to publish the required from anywhere using javascript

dates={some_value:value, another_value: value }
PubSub.publish(OFFLINE_BOOKING_DURATION, dates)

Here I just pass a dates object. You can pass anything. Then in react's componentDidMount state I subscribe to this

componentDidMount: function () {
    this.token = PubSub.subscribe(OFFLINE_BOOKING_DURATION, this.subscriber)
},

Here the first is object we are expecting and the callback

so here is the call back function here you can do anything like ajax call, set state, or anything

subscriber: function (msg, data) {
 #this method gets called on receiving data
 #we can access the data we passed like this
data.some_value},

And finally unsubscribe when component unmounts

componentWillUnmount: function () {
        PubSub.unsubscribe(this.token)
    }

This is how I implemented it. I no longer have the code but I hope you got the point.

1
Abdul Haseeb On

I don't really know what you're trying to do here exactly but if you just want to get values of your props from the component to your rails controller, do the following. You can set state of your props in your react component and send an ajax request whenever the user selects a date.