Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js this.props.variable is undefined in child Component

Tags:

reactjs

I set a minDate variable when I call the child component, which is a datePicker (doesn't matter). In the child I get this.props.minDate = undefined.

Am I missing something?

Here is my code:

Parent Component

getInitialState() {
    return {
        minDate: '',
        startDate: moment().subtract(30, 'days').format('YYYY-MM-DD'),
        endDate: moment().format('YYYY-MM-DD')
    };
},
componentWillMount() {
    ...
    this.setState({minDate: response});
    ...
},
render() {
    return (
        <DatePicker minDate={this.state.minDate} label="Start Date:"/>
    );
}

Child Component

getDefaultProps() {
    return {
        label: 'Date:',
        minDate: '',
    };
},

componentDidMount() {
    this.datePicker = $('#'+this.props.id);
    if (this.datePicker) {
        this.datePicker.datepicker({
            minDate: this.props.minDate
        });
    }
},

...

like image 820
David Simon Avatar asked Mar 04 '26 20:03

David Simon


1 Answers

The problem is that you are using an undefined minDate value when instantiating jQuery date picker.

Here's what is happening to the value of minDate:

Parent component sets the value of minDate to an empty string because it's defined so in the getInitialState method.

Parent component sets the value of minDate to the value of the response variable (probably undefined but I can't be sure as there is no other information to what the value of response is).

Child component takes the value of this.props.minDate when the child is mounted. At this point the value of this.props.minDate is either an empty string or undefined.

Finally jQuery date picker is then given the value of this.props.minDate in the componentDidMount method. The jQuery date picker is only instantiated once, so if the value of this.props.minDate changes over time it is not re-evaluated by the jQuery date picker.

like image 136
Enijar Avatar answered Mar 09 '26 00:03

Enijar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!