Skip to content Skip to sidebar Skip to footer

Updating React Component State Via External Interaction

How can the state/value of a React component change based on an external interaction? For example, if I have a date range component (screenshot below), and I've set dates, but now

Solution 1:

Lift state up is the typical answer. You end up with something like this:

classParentextendsComponent {

  // could get this from Redux if you wanted
  state = { dateRange: null };
  // could be a redux action if you wanted
  onDateRangeChange = dateRange =>this.setState({ dateRange });
  // could be a redux action if you wanted
  resetDateRange = () =>this.onDateRange(null);

  render() {
     const {dateRange} = this.state;

     return (
       <div><SomeComponentThatEventuallyRendersResetonReset={this.resetDateRange} /><SomeComponentThatEventuallyRendersDateControlonDateRangeChange={this.onDateRangeChange}dateRange={dateRange}
         /></div>
     );
  }
}

Your Reset control might be something like:

constResetControl = ({onClick}) => (<buttontype="button"onClick={onClick}>Reset</button);

Your date picker might be like:

classDatePickerextendsComponent {

   state = { any transient state you need before "submitting" changes to your parent };

   onSelection = (value) =>this.props.onDateRangeChange(value);

   render() {
      return<WhateveronChange={this.onSelection}onValue={this.props.dateRange} />;
   }
}

Post a Comment for "Updating React Component State Via External Interaction"