Search code examples
javascriptreactjsreact-dates

Access this.state values from child component


I am having trouble passing date values from a react-dates component to it's parent component.

Firstly, I would normally handle such a task with Redux but it's overkill for the project and would prefer a simple solution.

How can I pass onChange events from DateRangePicker to it's parent component?

Parent Component

...    
import DateRangePicker from './DatepickerRates'

class Rates extends Component {
    constructor(props) {
        super(props);
        this.state = { }
    }

    onChange(startDate, endDate) {
        this.setState({[startDate]: startDate});
        this.setState({[endDate]: endDate});
    }

    render() {
        console.log(`In ${this.state.startDate} - Out ${this.state.endDate}`)

        return (
            <Wrapper>
              <DateRangePicker onChange={this.onChange.bind(this)}/>
            </Wrapper>
        );
    }
}
export default Rates;

DateRangePicker

...
class DateRangePickerWrapper extends Component {
    constructor(props) {
        super(props);
        this.state = {
            focusedInput,
            startDate: props.initialStartDate,
            endDate: props.initialEndDate,
        }
        this.onDatesChange = this.onDatesChange.bind(this);
        this.onFocusChange = this.onFocusChange.bind(this);
    }

    onDatesChange({ startDate, endDate }) {
        const { stateDateWrapper } = this.props;
        this.props.onChange('startDate', this.state.startDate);
        this.props.onChange('endDate', this.state.endDate);
        this.setState({
          startDate: startDate && stateDateWrapper(startDate),
          endDate: endDate && stateDateWrapper(endDate),
        });
    }

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

        ...

        return (
            <div>
                <DateRangePicker
                    {...props}
                    onDatesChange={this.onDatesChange}
                    onFocusChange={this.onFocusChange}
                    focusedInput={focusedInput}
                    startDate={startDate}
                    endDate={endDate}
                />
            </div>
        );
    }
}

export default DateRangePickerWrapper;

Solution

  • here is working demo - https://codesandbox.io/s/vqw83my5l0 on your parent component set a prop like onChange={this.handleDropDownChange} and in child component onChange of date, in onDatesChangeand function set this.props.onChange(startDate, endDate) and you will get the data in handleDropDownChange()