Search code examples
javascriptreactjsreduxcomponentsreact-dates

Clearing input within React Component from a parent or grandparent Component


I'm have a filter form within my app that has normal input fields as well as a date range input (AirBnb's react-dates plugin). On submitting the filter form, I'd like the form to clear all fields. However, I haven't been able to find a way to access the fields within the react-dates component, since it is a child component.

So far, I have tried placing a "ref" on the Component as follows:

    <DateRangePickerWrapper ref="daterange"/>

And then selecting the ref through the following function:

filterButton(data,e){

    let refs = this.refs

    for(const key in refs){

      if(!(key === "daterange")){
         refs[key].value = ""
       }else{
         console.log(this.refs["daterange"])

       }
    }
}

However- I receive a "Connect" object upon log instead of the actual Component since I am using Redux.:

Connect {props: {…}, context: {…}, refs: {…}, updater: {…}, version: 15, …}

I tried adding the "forwardRef" option to the Component export, however- I still receive the Connect object...

export default connect(mapStateToProps, { forwardRef: true})(DateRangePickerWrapper);

If there is an easier way to reset the input besides going through the Components, I am more than happy to change to that method instead..

Thanks for your time!


Solution

  • From the react-dates README.md that you linked to in your question:

    <DateRangePicker
      startDate={this.state.startDate} // momentPropTypes.momentObj or null,
      endDate={this.state.endDate} // momentPropTypes.momentObj or null,
      // ... more props...
    />
    

    The props startDate and endDate accept null as a value, which has the effect of clearing the selected dates.