NSh
NSh

Reputation: 11

Not able to use predefined with bind function

I am using react-bootstrap-datetimerangepicker library with bind() to get the selected dates from the calendar but 'onApply' function of this library passes 2 params (event, picker) and in 'predefined' I am not getting startDate and endDate that suppose be coming in second param. And without bind its not working

<DatetimeRangePicker
    timePicker
    showDropdowns
    timePicker24Hour
    onApply={this.handleChange.bind(this, 'predefined')} />


handleChange(event, picker) {
        this.props.sendDateRanges(payload);
    }

https://github.com/luqin/react-bootstrap-datetimerangepicker

Upvotes: 0

Views: 81

Answers (1)

kngroo
kngroo

Reputation: 462

You need to bind this to your handleChange function for it to have lexical scope. Otherwise, handleChange has no notion of your component's this since it's block scoped. The second/subsequent arguments to bind are unnecessary in your case. What you're doing above is simply prepending the string 'predefined' to the arguments array. Instead, simply pass the bound function to the onApply prop instead.

onApply={this.handleChange.bind(this)}

If you're using es6 classes to define your component, a common pattern is to pre-bind all your event handlers and functions in the constructor.

constructor(props) {
   super(props)
   this.handleChange = this.handleChange.bind(this)
}
handleChange(event, picker) {
   //code
}
render() {
    return <div onChange={this.handleChange} />
}

If you want to get even fancier, you can use arrow function syntax which binds lexical scope implicitly. No need to call bind anywhere.

handleChange = (event, picker) => {
    //code
}
render() {
    return <div onChange={this.handleChange} />
}

Upvotes: 1

Related Questions