Search code examples
javascriptruby-on-railsreact-rails

changing props in react_component when using react_rails


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?


Solution

  • 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.