Search code examples
react-datepicker

How to change parent state(startDate) from child component? (using react DatePicker)


Audiences.js is parent Component, Condition.js is child. I want to change startDate(parent component) but "onDateChange" in Condition.js doesn't work.

Here is my code :

class Audiences extends Component {

state = {
    type: '',
    startDate: new Date()
}

handleDateChange = (date)=> {
    console.log(date)
    alert(date);
    this.setState({
        startDate: date
    });
}

render() {
    const { type, startDate } = this.state;
    const {
        handleDateChange
    } = this;

    return (
    
        <Condition type={type} date={startDate} onChange={handleDateChange} />
    );
}

}

const Condition = ({ type, date, onDateChange }) => {
    return (
        <div className="condition">
            App Usage Settings and Scope
            <hr />
            <DatePicker
                selected={date}
                onChange={onDateChange}
            />

        </div>
    );

};


Solution

  • Looks like you have a misnamed function... onChange={handleDateChange} should be onDateChange={handleDateChange}. Or conversely, you could've done const Condition = ({ type, date, onChange}).

    Disclaimer: would've commented but I don't have enough points. But to me that looks like the issue.