lost9123193 lost9123193 - 7 days ago 4
React JSX Question

Calling Parent Function in Child Component in React

I'm trying to pass a function called

updateTime
from my parent component to a child component.

The child component loads perfectly fine, but when
handleApply
is called, it tries to call
this.props.updateTime
but throws the error:

this.props.updateTime is not a function


Parent Component

class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
startDate: moment(),
endDate: moment().add(21, 'days'),
minDate: moment(),
};
this.updateTime = this.updateTime.bind(this);
}

updateTime(startDate, endDate) {
this.setState({
startDate: startDate,
endDate:endDate
});
}

render() {
return (
<div>
<DatePicker startDate={this.state.startDate} endDate={this.state.endDate} minDate={this.state.minDate} updateTime={this.props.updateTime}/>
</div>
)


Child Component:

class DatePicker extends Component {
constructor(props) {
super(props);
this.handleApply = this.handleApply.bind(this);
}


handleApply(event, picker) {
console.log("updating the time");
this.props.updateTime(picker.startDate, picker.endDate);
}


render() {
const {startDate, endDate, minDate, updateTime} = this.props;

let start = this.props.startDate.format('MMMM Do YYYY h:mm a');
let end = this.props.endDate.format('MMMM Do YYYY h:mm a');
let label = start + ' - ' + end;

let locale = {
format: 'MMMM do YYYY, h:mm:ss a',
separator: ' - ',
applyLabel: 'Apply',
cancelLabel: 'Cancel',
weekLabel: 'W',
customRangeLabel: 'Custom Range',
daysOfWeek: moment.weekdaysMin(),
monthNames: moment.monthsShort(),
firstDay: moment.localeData().firstDayOfWeek(),
};

return (
<div className="form-group">
<div className="date-time-range-picker">
<DatetimeRangePicker
timePicker
timePicker24Hour
showDropdowns
timePickerSeconds
locale={locale}
minDate = {this.props.minDate}
startDate={this.props.startDate}
endDate={this.props.endDate}
onApply={this.handleApply}>
<div className="input-group">
<input type="text" className="form-control" value={label}/>
<span className="input-group-btn">
<Button className="default date-range-toggle">
<i className="fa fa-calendar"/>
</Button>
</span>
</div>
</DatetimeRangePicker>
</div>
<div className="error">{error} </div>
</div>
);
}

Answer

You need to refer to the updateTime function properly in the parent component from:

<DatePicker ... updateTime={this.props.updateTime}/>

to:

<DatePicker ... updateTime={this.updateTime}/>