react-data-grid icon indicating copy to clipboard operation
react-data-grid copied to clipboard

DateRangeFilter

Open firdausmaarof opened this issue 8 years ago • 5 comments

  • Have you already searched for similar issues? Please help us out and double-check first!

  • Also, please don't be that person who deletes this template. It's here for a reason.

  • Thanks!


Which version of React JS are you using?

✅ Officially supported ✅

  • [ ] v15.4.x

⚠️ Not officially supported, expect warnings ⚠️

  • [ ] v15.5.x
  • [ ] v15.6.x

☣️ Not officially supported, expect warnings and errors ☣️

  • [ ] v16.x.x

Which browser are you using?

✅ Officially supported ✅

  • [ ] IE 9 / IE 10 / IE 11
  • [ ] Edge
  • [ ] Chrome

⚠️ Not officially supported, but "should work" ⚠️

  • [ ] Firefox
  • [ ] Safari

I'm submitting a ...

  • [ ] 🐛 Bug Report
  • [ ] 💡 Feature Request

👋 Need general support? Not sure about how to use React itself, or how to get started with the Grid? Please do not submit support request here. Instead see

https://github.com/adazzle/react-data-grid/blob/master/CONTRIBUTING.md


Issue Details

Please include:
- What the current behavior is
- What the desired behvaior is
- (If Bug) Steps to reproduce the issue
- (If Feature) The motivation / use case for the feature

We especially love screenshots / videos of problems, and remember
The Best Issue Is A Pull Request™

Hi,

I just want to know, how to use the DateRangeFilter? I cannot find any documentation on how to use it. Please help. Thanks.

firdausmaarof avatar May 22 '18 06:05 firdausmaarof

I had the same question, I don't think it's actually implemented/exported in the final code. I wound up implementing my own component.

Here's some example code for how I implemented this in my project:

/**
 * Parses a date string for comparison.
 *
 * @param {string} dateString - a date string from the <DateRangeFilter /> component.
 * @return {date} a native Date instance.
 */
const asDate = dateString => new Date(Date.parse(dateString));

export default class DateRangeFilter extends Component {
  static propTypes = {
    column: PropTypes.object,
    onChange: PropTypes.func.isRequired,
  }

  constructor(props) {
    super(props);

    this.state = {
      isOpen: false,
      startDate: '',
      endDate: '',
      originalStartDate: '',
      originalEndDate: '',
    };
  }

  /**
   * Returns true if a field is empty or if the selected
   * date range is invalid.
   */
  isDisabled = () => {
    return !this.state.startDate || !this.state.endDate || asDate(this.state.startDate) > asDate(this.state.endDate);
  }

  /**
   * Clears the current selection and hides the layer.
   */
  onClear = () => {
    this.setState({ isOpen: false, startDate: '', endDate: '' });
    this.props.onChange({ filterTerm: '', column: this.props.column });
  }

  /**
   * Stores the current form values and displays the layer.
   */
  onOpen = () => {
    this.setState({ isOpen: true, originalStartDate: this.state.startDate, originalEndDate: this.state.endDate });
  }

  /**
   * Resets the form values to their previous state and
   * hides the layer.
   */
  onClose = () => {
    this.setState({ isOpen: false, startDate: this.state.originalStartDate, endDate: this.state.originalEndDate });
  }

  /**
   * Returns a function that serves as an onChange handler
   * for a given field that updates the current state.
   *
   * @param {string} field - the name of the field to track.
   * @return {function} a function to serve as an onChange handler.
   */
  onChange = (field) => {
    return value => this.setState({ [field]: value });
  }

  /**
   * If the form is valid, hides the layer and calls
   * `this.props.onChange()` with the selections.
   *
   * @param {object} event - a native click event.
   */
  onSubmit = (event) => {
    event.preventDefault();

    const { startDate, endDate } = this.state;

    if (!this.isDisabled()) {
      this.setState({ isOpen: false });
      this.props.onChange({ filterTerm: { startDate, endDate }, column: this.props.column });
    }
  }

  render() {
    const error = (
      this.state.startDate &&
      this.state.endDate &&
      asDate(this.state.startDate) > asDate(this.state.endDate)
    ) ? 'The end date must be after the start date.' : null;

    return (
      <div className="DateFilter">
        <input
          placeholder="Start - End"
          value={this.state.startDate && this.state.endDate ? `${this.state.startDate} - ${this.state.endDate}` : ''}
          onClick={this.onOpen}
        />
        { this.state.isOpen && (
          <Layer
            closer
            onClose={this.onClose}
            className="DateFilter-layer"
            align="center"
          >
            <Box size="large" pad={{ vertical: 'medium' }}>
              <Heading align="start" tag="h3">
                Select a Date Range
              </Heading>
              <Box justify="between" direction="column">
                <FormField label="Start Date">
                  <DateTime
                    format="M/D/YYYY"
                    value={this.state.startDate}
                    onChange={this.onChange('startDate')}
                  />
                </FormField>
                <FormField label="End Date" error={error}>
                  <DateTime
                    format="M/D/YYYY"
                    value={this.state.endDate}
                    onChange={this.onChange('endDate')}
                  />
                </FormField>
              </Box>
              <Footer direction="row" justify="between" align="center">
                <Button
                  label="Clear Dates"
                  onClick={this.onClear}
                />
                <Button
                  primary
                  label="Apply Dates"
                  onClick={this.onSubmit}
                  disabled={this.isDisabled()}
                  className={`${this.isDisabled() ? 'grommetux-button--disabled' : ''}`}
                />
              </Footer>
            </Box>
          </Layer>
        )}
      </div>
    );
  }
}

const tableColumns = [
  {
    key: 'updated_at',
    name: 'Last Updated',
    filterable: true,
    sortable: true,
    resizable: true,
    filterRenderer: DateRangeFilter,
  }
];

<ReactDataGrid
  ...
  tableColumns={tableColumns}
/>

As you can see, we're using grommet component library, but you can basically render any component, as long as it calls props.onChange with the expected function signature. In our case, we render an input (top of the render() function) and when it's clicked, open a modal to handle specific date selections.

this.props.onChange({ filterTerm: { startDate, endDate }, column: this.props.column });

SteveAquino avatar May 27 '18 20:05 SteveAquino

Seems like you'd need a filterValues function as well:


  filterValues = (row, columnFilter, columnKey) => {
    if (columnFilter.filterTerm == null) {
      return true;
    }

    const actualValue = asDate(row[columnKey]);
    const filterStartDate = asDate(columnFilter.filterTerm.startDate);
    const filterEndDate = asDate(columnFilter.filterTerm.endDate);

    return (
      actualValue >= filterStartDate &&
      actualValue <= filterEndDate
    );
  };

and adjusted onSubmit:

 onSubmit = event => {
    event.preventDefault();

    const { startDate, endDate } = this.state;

    if (!this.isDisabled()) {
      this.setState({ isOpen: false });
      this.props.onChange({
        filterTerm: { startDate, endDate },
        column: this.props.column,
        filterValues: this.filterValues
      });
    }
  };

jeznag avatar Jun 15 '18 07:06 jeznag

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Please reopen this if you feel it has been incorrectly closed and we will do our best to look into it. Thank you for your contributions.

stale[bot] avatar Jul 15 '18 07:07 stale[bot]

So is it not implemented?

drewboardman avatar Jul 17 '18 15:07 drewboardman

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Please reopen this if you feel it has been incorrectly closed and we will do our best to look into it. Thank you for your contributions.

stale[bot] avatar Aug 16 '18 16:08 stale[bot]