import * as React from "react";
import moment from "moment";
import TextField from "#mui/material/TextField";
import { AdapterDayjs } from "#mui/x-date-pickers/AdapterDayjs";
import { LocalizationProvider } from "#mui/x-date-pickers/LocalizationProvider";
import { DatePicker } from "#mui/x-date-pickers/DatePicker";
export default function BasicDatePicker() {
const [value, setValue] = React.useState(null);
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
label="Basic example"
value={value}
onChange={(newValue) => {
console.log("newvalue", newValue);
console.log("newvalue-moment", moment(newValue).format("YYYY-MM-DD"));
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
);
}
I am using Mui Datepicker Basic and trying to convert the selected value into YYYY-MM-DD format using moment.js. I have to extract only date and use as payload, But it is not working here and catching the current date.
you can use dayjs library (small library, 7.2k) as moment is very costly (232kb)
import using import dayjs from 'dayjs'
if using Typescript , you can get the type as well
import dayjs, { Dayjs } from 'dayjs'
use it like dayjs(selectedDate).format('MM/DD/YYYY')
Related
I want to set value in value props <DatePicker>. But if i set value, and if i click the date picker, calendar will be infinite loop to the future.
i have use DefaultValue and value props, but produce same error
import React from "react";
import "./index.css";
import type { DatePickerProps } from "antd";
import { DatePicker, Space } from "antd";
import moment from "moment";
const onChange: DatePickerProps["onChange"] = (date, dateString) => {
console.log(date, dateString);
};
const day = moment();
const format = "DD.MM.YYYY";
const App: React.FC = () => (
<Space direction="vertical">
<DatePicker
onChange={onChange}
format={format}
defaultValue={moment(day)}
/>
</Space>
);
export default App;
You can try here
SANBOX
and the picture is here
PICTURE
i have use DefaultValue and value props, but produce same error.
i have delete DefaultValue and value props and calendar is normal, but i cannot set value from beginning
As per the documentation and the below error from the defaultValue when using moment js shows that the accepted format is day js
Type 'string' is not assignable to type 'Dayjs'.
To resolve above issue of showing date , follow below steps
Import dayjs
Using defaultvalue attribute, assign current date using dayjs
import React from "react";
import "./index.css";
import type { DatePickerProps } from "antd";
import { DatePicker, Space } from "antd";
//import moment from "moment";
import dayjs from "dayjs";
const onChange: DatePickerProps["onChange"] = (date, dateString) => {
console.log(date, dateString);
};
const format = "DD.MM.YYYY";
const App: React.FC = () => (
<Space direction="vertical">
<DatePicker onChange={onChange} format={format} defaultValue={dayjs()} />
</Space>
);
export default App;
Updated the codesandbox for your reference - https://codesandbox.io/s/basic-antd-5-1-7-forked-b87dbv?file=/demo.tsx
Documentation link for reference- https://ant.design/components/date-picker
How Can I set the antd Datepicker language to french?
I tried this :
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import moment from "moment";
import { DatePicker, Space, ConfigProvider } from "antd";
import frFR from "antd/lib/locale/fr_FR";
function onChange(date, dateString) {
console.log(date, dateString);
}
ReactDOM.render(
<Space direction="vertical">
<ConfigProvider locale={frFR}>
<DatePicker
onChange={onChange}
defaultValue={moment("2015-01-01", "YYYY-MM-DD")}
/>
</ConfigProvider>
</Space>,
document.getElementById("container")
);
The preview language is still in English.
Here is a running code:
https://codesandbox.io/s/basic-antd-datepicker-language-n9ue7
From the ant design doc
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
<DatePicker locale={locale} />;
https://ant.design/components/date-picker/#Localization
I'm new to react and now I wanna be able to have a reusable component for date input, but i cannot get the values back from the component to the register.
Here is my form code:
import React, { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { Button } from "#mui/material";
import FDate from "../../Components/Forms/FDate";
function AltaArtista() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
const onSubmit = async (data) => {
try {
console.log(data);
} catch (e) {}
};
return (
<div>
<FDate
label='Fecha de Nacimiento'
register={{ ...register("nacimiento", { required: true }) }}
/>
<Button variant='contained' type='submit'>
date input
</Button>
</form>
</div>
);
}
And here is my FDate component
import * as React from "react";
import { TextField } from "#mui/material";
import DatePicker from "#mui/lab/DatePicker";
import AdapterDateFns from "#mui/lab/AdapterDateFns";
import LocalizationProvider from "#mui/lab/LocalizationProvider";
function Fdate(props) {
const [value, setValue] = React.useState(new Date());
const handleDate = (newValue) => {
setValue(newValue);
console.log(newValue);
};
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label={props.label}
value={value}
onChange={handleDate}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
);
}
export default Fdate;
When I print newValue in handleDate I can get the time selected in datePicker, but the value that returns to the form is the date selected when the app starts and it doesn't change, any thoughts will be very much appreciated.
In your Fdate component, you're not using the register prop that you're passing it down from AltaArtista. Form state is controlled by the useForm hook and so you don't need to separately control it inside of 'Fdate'. But you should set the default (initial) value of nacimiento when declaring useForm
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
defaultValues: {nacimiento: new Date()}
});
and then spread your props inside Fdate:
import * as React from "react";
import { TextField } from "#mui/material";
import DatePicker from "#mui/lab/DatePicker";
import AdapterDateFns from "#mui/lab/AdapterDateFns";
import LocalizationProvider from "#mui/lab/LocalizationProvider";
function Fdate(props) {
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
{...props}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
);
}
export default Fdate;
I'm trying to use DatePicker of #material-ui/pickers from React but it doesn't work.
I tried using the exact same code as in the documentation (https://material-ui-pickers.dev/getting-started/usage):
import React, { useState } from 'react';
import DateFnsUtils from '#date-io/date-fns'; // choose your lib
import {
DatePicker,
TimePicker,
DateTimePicker,
MuiPickersUtilsProvider,
} from '#material-ui/pickers';
export default function Relatorio() {
const [selectedDate, handleDateChange] = useState(new Date());
return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DatePicker value={selectedDate} onChange={handleDateChange} />
<TimePicker value={selectedDate} onChange={handleDateChange} />
<DateTimePicker value={selectedDate} onChange={handleDateChange} />
</MuiPickersUtilsProvider>
);
}
I get this error (screenshot attached): The above error occurred in the <MuiPickersUtilsProvider> component
In codeSandBox it doesn't work with #date-io/date-fns versions above 2.0.0, I am using version 1.3.12 which is supposed to work.
Error message:
I am currently using material ui on the web and I use the KeyboardDatePicker API and it works perfectly, but the names of the months and the text of the buttons are shown in English and I want to change them to Spanish. I read the API documentation but I can't find information about it.
Anyone know how to change the language?
Another solution which worked for me is using date-fns/locale/*. The documentation can be found here.
For example in german:
import {KeyboardDatePicker, MuiPickersUtilsProvider} from "#material-ui/pickers";
import DateFnsUtils from "#date-io/date-fns";
import deLocale from "date-fns/locale/de";
render () {
return
(
<MuiPickersUtilsProvider utils={DateFnsUtils} locale={deLocale}>
.
.
.
</MuiPickersUtilsProvider>
)
}
Result:
Try importing spanish moment locale and then using it in MuiPickersUtilsProvider:
import React from "react";
import ReactDOM from "react-dom";
import {
KeyboardDatePicker,
MuiPickersUtilsProvider
} from "#material-ui/pickers";
import MomentUtils from "#date-io/moment";
import "moment/locale/es";
import "./styles.css";
function App() {
return (
<div className="App">
<MuiPickersUtilsProvider locale="es" utils={MomentUtils}>
<KeyboardDatePicker />
</MuiPickersUtilsProvider>
</div>
);
}
For spanish the solution that worked for me is the following
import 'date-fns';
import React from 'react';
import { MuiPickersUtilsProvider, KeyboardDatePicker } from '#material-ui/pickers';
import FormControl from '#material-ui/core/FormControl';
import DateFnsUtils from '#date-io/date-fns';
import deLocale from "date-fns/locale/es";
import {useStyles} from './style';
export default function FormControlDate(props) {
const classes = useStyles();
return (
<FormControl className={classes.formControl} >
<MuiPickersUtilsProvider locale={deLocale} utils={DateFnsUtils} >
<KeyboardDatePicker
disableToolbar
variant="inline"
format="dd/MM/yyyy"
margin="normal"
id={props.name}
name={props.name}
key={props.name}
label={props.label}
value={props.value}
onChange={date=>{
props.handleChange({"target":{"name":props.name,"value":date}})
}}
KeyboardButtonProps={{
'aria-label': 'change date',
}}
/>
</MuiPickersUtilsProvider>
</FormControl>
)
}