Create Date Range Picker in React

Date range picker component creates a dropdown menu or calendar from which a user can select a range of dates.

Date Range Picker Component in React

First we will create basic functional components required in our date range picker like Head…


This content originally appeared on DEV Community and was authored by Chetan Rohilla

Date range picker component creates a dropdown menu or calendar from which a user can select a range of dates.

Date Range Picker Component in React

First we will create basic functional components required in our date range picker like Heading, Day, Days. So, create file date-range-picker-components.js in your project.

const Heading = ({date, changeMonth, resetDate}) => (
  <nav className="daterangepicker--nav">
    <a onClick={() => changeMonth(date.month() - 1)}>&#8249;</a>
    <h1 onClick={() => resetDate()}>{date.format('MMMM')} <small>{date.format('YYYY')}</small></h1>
    <a onClick={() => changeMonth(date.month() + 1)}>&#8250;</a>
  </nav>
);

const Day = ({currentDate, date, startDate, endDate, onClick}) => {
  let className = [];

  if (moment().isSame(date, 'day')) {
    className.push('active');
  }

  if (date.isSame(startDate, 'day')) {
    className.push('start');
  }

  if (date.isBetween(startDate, endDate, 'day')) {
    className.push('between');
  }

  if (date.isSame(endDate, 'day')) {
    className.push('end');
  }

  if (! date.isSame(currentDate, 'month')) {
    className.push('muted');
  }

  return (
    <span onClick={() => onClick(date)} currentDate={date} className={className.join(' ')}>{date.date()}</span>
  )
};

const Days = ({date, startDate, endDate, onClick}) => {
  const thisDate = moment(date);
  const daysInMonth = moment(date).daysInMonth();
  const firstDayDate = moment(date).startOf('month');
  const previousMonth = moment(date).subtract(1, 'month');
  const previousMonthDays = previousMonth.daysInMonth();
  const nextsMonth = moment(date).add(1, 'month');
  let days = [];
  let labels = [];

  for (let i = 1; i <= 7; i++) {
    labels.push(<span className="label">{moment().day(i).format('ddd')}</span>);
  }

  for (let i = firstDayDate.day(); i > 1; i--) {
    previousMonth.date(previousMonthDays - i + 2);

    days.push(
      <Day key={moment(previousMonth).format('DD MM YYYY')} onClick={(date) => onClick(date)} currentDate={date} date={moment(previousMonth)} startDate={startDate} endDate={endDate} />
    );
  }

  for (let i = 1; i <= daysInMonth; i++) {
    thisDate.date(i);

    days.push(
      <Day key={moment(thisDate).format('DD MM YYYY')} onClick={(date) => onClick(date)} currentDate={date} date={moment(thisDate)} startDate={startDate} endDate={endDate} />
    );
  }

  const daysCount = days.length;
  for (let i = 1; i <= (42 - daysCount); i++) {
    nextsMonth.date(i);
    days.push(
      <Day key={moment(nextsMonth).format('DD MM YYYY')} onClick={(date) => onClick(date)} currentDate={date} date={moment(nextsMonth)} startDate={startDate} endDate={endDate} />
    );
  }

  return (
    <nav className="daterangepicker--days">
      {labels.concat()}
      {days.concat()}
    </nav>
  );
};

export default { Heading, Days };

Create Date Range Picker in React

Now, we can import the components defined above (date-range-picker-components is the filename of our components).

import { Heading, Days } from './date-range-picker-components';

class DateRangePicker extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      date: moment(),
      startDate: moment().subtract(5, 'day'),
      endDate: moment().add(3, 'day')
    };
  }

  resetDate() {
    this.setState({
      date: moment()
    });
  }

  changeMonth(month) {
    const {date} = this.state;

    date.month(month);

    this.setState(
      date
    );
  }

  changeDate(date) {
    let {startDate, endDate} = this.state;

    if (startDate === null || date.isBefore(startDate, 'day') || ! startDate.isSame(endDate, 'day')) {
      startDate = moment(date);
      endDate = moment(date);
    } else if (date.isSame(startDate, 'day') && date.isSame(endDate, 'day')) {
      startDate = null;
      endDate = null;
    } else if (date.isAfter(startDate, 'day')) {
      endDate = moment(date);
    }

    this.setState({
      startDate,
      endDate
    });
  }

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

    return (
      <div className="daterangepicker">
        <Heading date={date} changeMonth={(month) => this.changeMonth(month)} resetDate={() => this.resetDate()} />

        <Days onClick={(date) => this.changeDate(date)} date={date} startDate={startDate} endDate={endDate} />
      </div>
    );
  }
}

Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please visit my website.

Thanks:)
Happy Coding:)


This content originally appeared on DEV Community and was authored by Chetan Rohilla


Print Share Comment Cite Upload Translate Updates
APA

Chetan Rohilla | Sciencx (2022-04-06T05:14:29+00:00) Create Date Range Picker in React. Retrieved from https://www.scien.cx/2022/04/06/create-date-range-picker-in-react/

MLA
" » Create Date Range Picker in React." Chetan Rohilla | Sciencx - Wednesday April 6, 2022, https://www.scien.cx/2022/04/06/create-date-range-picker-in-react/
HARVARD
Chetan Rohilla | Sciencx Wednesday April 6, 2022 » Create Date Range Picker in React., viewed ,<https://www.scien.cx/2022/04/06/create-date-range-picker-in-react/>
VANCOUVER
Chetan Rohilla | Sciencx - » Create Date Range Picker in React. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/06/create-date-range-picker-in-react/
CHICAGO
" » Create Date Range Picker in React." Chetan Rohilla | Sciencx - Accessed . https://www.scien.cx/2022/04/06/create-date-range-picker-in-react/
IEEE
" » Create Date Range Picker in React." Chetan Rohilla | Sciencx [Online]. Available: https://www.scien.cx/2022/04/06/create-date-range-picker-in-react/. [Accessed: ]
rf:citation
» Create Date Range Picker in React | Chetan Rohilla | Sciencx | https://www.scien.cx/2022/04/06/create-date-range-picker-in-react/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.