Unform

React DatePicker

React DatePicker

React DatePicker is a very simple library that provides a fully customizable Date & Time input with a cool picker.

⚠️ All examples below are using TypeScript. If you're not using it, you can remove all type definitions from the component definition.

Example

import React, { useRef, useState, useEffect } from 'react';
import ReactDatePicker, { ReactDatePickerProps } from 'react-datepicker';
import { useField } from '@unform/core';
import 'react-datepicker/dist/react-datepicker.css';
interface Props extends Omit<ReactDatePickerProps, 'onChange'> {
name: string;
}
export default function DatePicker({ name, ...rest }: Props) {
const datepickerRef = useRef(null);
const { fieldName, registerField, defaultValue, error } = useField(name);
const [date, setDate] = useState(defaultValue || null);
useEffect(() => {
registerField({
name: fieldName,
ref: datepickerRef.current,
path: 'props.selected',
clearValue: (ref: any) => {
ref.clear();
},
});
}, [fieldName, registerField]);
return (
<ReactDatePicker
ref={datepickerRef}
selected={date}
onChange={setDate}
{...rest}
/>
);
};
Edit this page on GitHub

On this page