Datepicker allows the user to select a date or date range from a calendar.
import { DatePicker, DateRangePicker } from "@wfp/react"
The Datepicker allows the user to select a date or date range from a calendar.
We recommend react-datepicker for DatePickers and DateRangePickers. It is a well maintained library with a lot of features and customizability and is used in the examples below. It uses date-fns for date manipulation.
Initialize with loading classes to load the styling from WFP UI
Make sure to also install react-datepicker and import it in your project.
import ReactDatePicker from "react-datepicker";
It also takes all the properties of the Input component.
() => { const [date, setDate] = useState(null); return ( <DatePicker labelText="DatePicker" helperText="This is the helperText" datePicker={ReactDatePicker} startDate={date} setStartDate={(newDate) => setDate(newDate)} /> ); };
() => { const [startdate, setStartDate] = useState(null); const [enddate, setEndDate] = useState(null); return ( <DateRangePicker labelText="DateRangePicker" helperText="This is the helperText" datePicker={ReactDatePicker} startDate={startdate} endDate={enddate} setStartDate={(newDate) => setStartDate(newDate)} setEndDate={(newDate) => setEndDate(newDate)} /> ); };
The date picker relies on date-fns internationalization to localize its display components. By default, the date picker will use the locale globally set, which is English. Provided are 3 helper methods to set the locale:
registerLocale
(string, object): loads an imported locale object from date-fnssetDefaultLocale
(string): sets a registered locale as the default for all datepicker instancesgetDefaultLocale
: returns a string showing the currently set default localeExample:
import { registerLocale, setDefaultLocale } from "react-datepicker";import es from 'date-fns/locale/es';registerLocale('es', es)<DatePickerlocale="es"/>
DatePicker can be used with react-hook-form by using the Controller
component.
() => { const { control, handleSubmit } = useForm(); return ( <> <form onSubmit={handleSubmit((data) => console.log(data) )} > <Controller name="ReactDatepicker" control={control} defaultValue={null} render={({ field: { onChange, value } }) => ( <DatePicker labelText="DatePicker" helperText="Helper text" startDate={value} datePicker={ReactDatePicker} setStartDate={(date) => onChange(date)} /> )} /> </form> </> ); };