user5938020
user5938020

Reputation: 63

React: How to filter events according to date

I am displaying events in a table in a js file like this:

 // index.component.js

import React, { Component } from 'react';
import axios from 'axios';
import TableRow from './TableRow';
import moment from 'moment';
export default class Index extends Component {

constructor(props) {
  super(props);
  this.state = {event: []};
}
componentDidMount(){
  axios.get('http://localhost:4000/event')
    .then(response => {
      this.setState({ event: response.data });

    })
    .catch(function (error) {
      console.log(error);
    })
}


tabRow(){
  var events = this.state.event
  events.sort((a,b) => {return new Date(a.startDate) - new 
Date(b.startDate)} ) ;
  return events.map(function(object, i){
  return <TableRow obj={object} key={i} />;
});
}


render() {
  return (
    <div>
      <table className="table table-striped" style={{ marginTop: 20 , width:700}}>
        <tbody>
          { this.tabRow() }
        </tbody>
      </table>
    </div>
  );
}

}

My table.js

// TableRow.js


class TableRow extends Component {
constructor(props) {
    super(props);
 }

render() {
return (

    <tr>
      <td>
        {this.props.obj.event_name} 
      </td>
      <td>{ moment(this.props.obj.startDate).format("MMMM D, Y") }</td>
      <td>
        <button onClick={this.delete} className="btn btn- 
      danger">Delete</button>
      </td>
     </tr>
     );
     }
      }
   export default TableRow;

Right now, I am using the sort function of events, as you can see in the code provided above, to sort the events according to dates, the oldest event being the first one to list. That is working allright. I would like to filter the array, so that the events that have already gone by, do not appear in my final table. How can I compare it to present date and filter out the old events?

Upvotes: 3

Views: 33214

Answers (1)

Jan Peter
Jan Peter

Reputation: 920

You need to subtract the current date from your event date and check if it is smaller than 0. If it is, it is in the past and you can ignore it. So the filter function should look something like this:

const dates = ["2018-09-12", "2018-10-18", "2018-12-30"];
const filteredDates = dates.filter(d => new Date(d) - new Date() > 0);

And that's what it would look like in your case:

events = events.filter(a => new Date(a.startDate) - new Date > 0);

Upvotes: 10

Related Questions