DEV Community

sagarkhadka
sagarkhadka

Posted on

How to use Date-Range in react ?

Date-Range is a npm package that lets us to use and display modern looking calendar window on our website. To setup the Date-Range following steps

Step 1: First do npm i react-date-range install the package

Step 2: Import calendar along with its CSS file in the component file

import { Calendar, DateRange } from 'react-date-range'
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a useState for the calendar.

import React, { useState } from 'react'

const [date, setDate] = useState([
  {
    startDate: new Date(),
    endDate: new Date(), // Use null if you don't want to have endDate
    key: 'selection'
  }
])
Enter fullscreen mode Exit fullscreen mode

Step 4: We have to also add numbers npm add date-fns

Step 5: Add following component with a className to position using CSS. Note: that props name should be same that we created in step 3. const [date, setDate] = useState

<DateRange editableDateInputs={true} onChange={(item) => setDate([item.selection])} moveRangeOnFirstSelection={false} ranges={date} className="date" />
Enter fullscreen mode Exit fullscreen mode

Step 6: If you want to show the selected date in format import โ€˜date-fnsโ€™

import { format } from 'date-fns';

Step 7: To display selected date

{${format(date[0].startDate, "MM/dd/yyyy")} to ${format(date[0].endDate, "MM/dd/yyy")}}

The above method only creates static calendar window. If we want to open date-range on click then add following code.

Step 8: Make a useState hook to open and close calendar window

const [openDate, setOpenDate] = useState(false)

Step 9: Wrap date component with {openDate && <DateRange />} and set onClick={()=>setOpenDate(!openDate)}

Your final code should look like this

import React, { useState } from 'react'
import { DateRange } from 'react-date-range'
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { format } from 'date-fns';

const Component = () => {
  const [openDate, setOpenDate] = useState(false)
  const [date, setDate] = useState([
    {
      startDate: new Date(),
      endDate: new Date(),
      key: 'selection',
    }
  ])

  return (
    <div className='calendar'>
      <span onClick={ ()=>setOpenDate(!openDate) }>{ `${format(date[0].startDate, "MM/dd/yyyy")} to ${format(date[0].endDate, "MM/dd/yyy") }` }</span>
      { openDate && <DateRange editableDateInputs={ true } onChange={ (item) => setDate([item.selection]) } moveRangeOnFirstSelection={ false } ranges={ date } className="date" /> }
    </div>
  )
}

export default Header
Enter fullscreen mode Exit fullscreen mode

Top comments (0)