Implement Primereact Datepicker In React-JS

Hello developers, in this blog we will learn how we can use datepicker in react using the prime-react library

First, create a new app using the following command:

npx create-react-app prime-react-calendar

Now install these packages in your app:

npm i primereact
npm i primeicons
npm i primeflex

Now copy and paste this code into your file:

import 'primeicons/primeicons.css';
import 'primereact/resources/themes/lara-light-indigo/theme.css';
import 'primereact/resources/primereact.css';
import 'primeflex/primeflex.css';
import React, { useState } from 'react';
import { Calendar } from 'primereact/calendar';

const MultiSelection = () => {
  const [date, setDate] = useState(new Date())

  return (
    <div className="card flex justify-content-center">
      <Calendar value={date} onChange={(date) => setDate(date.value)} />
    </div>
  )
}

export default MultiSelection

Demo: (Basic)

You can also add min and max date validation to prevent users from selecting past dates or future dates

<Calendar value={date} onChange={(date) => setDate(date.value)} minDate={new Date()} maxDate={new Date(new Date().setDate(new Date().getDate() + 7))} />

Demo: (min and max date validations)

Exclude particular days or dates:

You can also restrict users to select particular dates or days with disabledDates and disabledDays options

disabledDates property should be an array of dates and disabledDays property should be an array of numbers

const disabledDays = [0, 6]
const disabledDates = [
   new Date(new Date().setDate(new Date().getDate() + 1)),
   new Date(new Date().setDate(new Date().getDate() + 2)),
   new Date(new Date().setDate(new Date().getDate() + 3)),
   new Date(new Date().setDate(new Date().getDate() + 4)),
   new Date(new Date().setDate(new Date().getDate() + 5)),
   new Date(new Date().setDate(new Date().getDate() + 6)),
   new Date(new Date().setDate(new Date().getDate() + 7))
]
<Calendar value={date} onChange={(date) => setDate(date.value)} disabledDays={disabledDays} disabledDates={disabledDates} />,

This will disable every Sunday and Saturday of the month and seven days from today’s date

Demo: (Excluded days and dates)

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories