How to pas props to MUI Datepicker - javascript

I tried changing the mui datepicker to a different format, but it always fails.
this code work for me
const Step2 = ({handlechange,value: {startTime}}) =>
{
return(
<TextField
fullWidth
required
color="success"
size="small"
label="Start Time"
name='startTime'
type="datetime-local"
value={startTime || '2022-06-24T10:30' }
InputLabelProps={{
shrink: true,
}}
margin="normal"
onChange={handlechange}
/>
)
}
export default Step2
but how to implement to MUI Datetime picker to this
const Step2 = ({handlechange,value: {startTime}}) =>
{
const [value, setValue] = React.useState(new Date());
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DateTimePicker
renderInput={(props) => <TextField {...props} />}
label="DateTimePicker"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}/>
</LocalizationProvider>)
}
export default Step2

Related

How can I prevent my datepicker getting re-focussed after clicking another input

I have a Datepicker of Material that opens if you click on the textfield it belongs to. If you try to select another textfield while the datepicker is opened it will target/focus back to the datepicker.
Note: This issue is also for targeting nothing, it will refocus the datepicker again after closing it.
Example Demo: https://stackblitz.com/edit/react-b4xpki?file=demo.tsx
Code:
`
export default function BasicDatePicker() {
const [value, setValue] = React.useState<Dayjs | null>(null);
const [open, setOpen] = React.useState(false);
return (
<LocalizationProvider dateAdapter={AdapterDayjs}>
<TextField placeholder='Click here while datepicker is opened' fullWidth={true} sx={{mb:2, mr: 2}}/>
<DatePicker
label="Basic example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
open={open}
onOpen={() => setOpen(true)}
onClose={() => setOpen(false)}
renderInput={(props) => (
<TextField {...props} onClick={(e) => setOpen(true)} />
)}
/>
</LocalizationProvider>
);
}
So how to reproduce to problem?
Click op the datepicker (not the icon)
Click on another textfield
Watch how the target/focus is back on the datepicker
You can create focus named state so can control in onFocus at <TextField />
firstly, create focus named state:
const [focus, setFocus] = useState(false);
TextField: if open is false in onFocus, currentTarget shouldn't be focus.
<TextField
{...props}
onFocus={(e) => {
setFocus(open);
if (!open) {
e.currentTarget.blur();
return;
}
}}
focused={focus}
onClick={(e) => setOpen((prev) => !prev)}
/>
if the value changes in DatePicker, focus should be true.
<DatePicker
label="Basic example"
value={value}
onChange={(newValue) => {
setValue(newValue);
setFocus(true);
}}
...otherProps
/>
link: https://stackblitz.com/edit/react-b4xpki-rirdxn?file=demo.tsx

Calendar popup needed to be closed after selecting the date

The calendar popup is not getting closed after selecting the date and it's wrapped in a label tag with an image and the calendar component. if I'm removing the label tag image tag is not activating the calendar popup.
`<label style={{width:"100%"}}>
<DatePicker
dateFormat="dd/MM/yyyy"
placeholderText="Select Date"
onChange={onChange}
minDate={props.minDate ? props.minDate : null}
maxDate={props.maxDate ? props.maxDate : null}
className={props.className}
style={{ width: '100%', marginTop:"-10px" }}
selected={props.value && props.value !== "" ? new Date(props.value) : null}
showDisabledMonthNavigation
/>
<img
src="./images/calendar.png"
className="custom-input-icon img-fluid"
alt="c"
style={{ top: '25px' }}
/>
</label>`
so I tried calling the component using onClick event but it's not really working. i don't know how to do it. any help would be much appreciated.
<>
<DatePicker
dateFormat="dd/MM/yyyy"
placeholderText="Select Date"
onChange={onChange}
minDate={props.minDate ? props.minDate : null}
maxDate={props.maxDate ? props.maxDate : null}
className={props.className}
style={{ width: '100%', marginTop:"-10px" }}
selected={props.value && props.value !== "" ? new Date(props.value) : null}
showDisabledMonthNavigation
/>
<img onClick={handleclick}
src="./images/calendar.png"
className="custom-input-icon img-fluid"
alt="c"
style={{ top: '25px' }}
/>
</>
handling click???
const handleclick = () => {console.log('ello');
you need to wrap it like this but if i press the preselected date (current date) it won't close the popup so i need to click away to close it
import { DatePicker, LocalizationProvider } from '#mui/lab'
import roLocale from 'date-fns/locale/ro';
import DateAdapter from '#mui/lab/AdapterDateFns';
import { TextField } from '#mui/material';
const [error, setError] = useState(false)
const [value, setValue] = useState<Date | null>(null)
const handleChange = (newValue: Date | null) => {
setValue(newValue)
}
{/* const handleValidation = () => {
if (error) {
alert(error)
}
} */}
<LocalizationProvider dateAdapter={DateAdapter} locale={roLocale}>
<DatePicker inputFormat="dd/MM/yyyy"
label={label}
openTo="year"
value={value}
// onError={err => setError(err ? true : false)}
onChange={(newValue: Date | null) => handleChange(newValue)}
maxDate={MIN_DATE}
minDate={MAX_DATE}
renderInput={(params) => <TextField variant="standard"
// onBlur={handleValidation}
fullWidth
required={true}
color="secondary"
{...params} />} />
</LocalizationProvider>

MUI DatePicker's shouldDisableDate prop leading to error

<Controller
name="toDate"
control={control}
defaultValue={null}
render={({ field }) => (
<DatePicker
format="DD/MM/yyyy"
value={field.value}
onChange={(e) => { setToDate(e); field.onChange(e); }}
minDate={fromDate}
shouldDisableDate={fromDate}
/>
)}
{...register("toDate",{ required: true })}
/>
I used the shouldDisableProp to disable the date which is selected inside another datepicker whose value is stored in a state variable 'fromDate'.
But when I press the datepicker it is leading to this error.
The minDate is working perfectly fine using the fromDate state variable.
The shouldDisableDate method receives a date param and expect a boolean.
import * as React from "react";
import TextField from "#mui/material/TextField";
import AdapterDateFns from "#mui/lab/AdapterDateFns";
import LocalizationProvider from "#mui/lab/LocalizationProvider";
import DatePicker from "#mui/lab/DatePicker";
export default function BasicDatePicker() {
const [value, setValue] = React.useState<Date | null>(null);
const [fromDate, setFromDate] = React.useState<Date | null>(null);
return (
<>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="From Date"
value={fromDate}
onChange={(newValue) => {
setFromDate(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
<br />
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="To Date"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
minDate={fromDate}
shouldDisableDate={(dateParam) => {
//your_condition here
//return true to disabled and false to enable
const fromFormatted = fromDate.toISOString().split("T")[0];
const currentDate = dateParam.toISOString().split("T")[0];
return fromFormatted === currentDate ? true : false;
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</>
);
}
UpdatedCode
So do something like that and you will achieve your goal.
In your case, compare dateParam with your fromDate var, to return true or false and disable or not the date.
Edit: Now is adapted to your real case. Just check it out.

How can i change the both value change and function call in a single onChange

Here is the code, and i want to call apifetcher at the same time when the value of the city changes.how to do that?? is it possible
The value of the city should replace the 'q' value. And after that both the city and the API are passing to an another file.what should I add or remove.
import React, { useState } from "react";
import Cities from "./citylist";
import Autocomplete from "#material-ui/lab/Autocomplete";
import TextField from "#material-ui/core/TextField";
import Content from "./content";
const SearchBar = () => {
const [city, setcity] = useState("");
const [api, setapi] = useState(
`http://api.openweathermap.org/data/2.5/forecast?q=Kurunegala,LK& mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`
);
console.log(city);
Content(city, api);
const apiFtecher = () => {
return setapi(
`http://api.openweathermap.org/data/2.5/forecast?q=${city},LK&mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`
);
};
return (
<div style={{ width: 300 }}>
<Autocomplete
freeSolo
id="free-solo-2-demo"
disableClearable
options={Cities.map((option) => option.name)}
renderInput={(params) => (
<TextField
{...params}
label="city"
margin="normal"
variant="outlined"
InputProps={{ ...params.InputProps, type: "search" }}
onChange={(e) => setcity(e.target.value)}
onBlur={(e) => setcity(e.target.value)}
/>
)}
/>
</div>
);
};
export default SearchBar;
There doesn't seem to be a need for the city state variable.
To call apiFtecher[sic] on every change of the input, you would do something like this:
const apiFtecher = e => {
const city = e.target.value;
return (
setapi(`http://api.openweathermap.org/data/2.5/forecast?q=${city},LK&mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`)
);
}
And update the element to:
<TextField
{...params}
label="city"
margin="normal"
variant="outlined"
InputProps={{ ...params.InputProps, type: 'search' }}
onChange={apiFtecher}
/>

Getting the value in the React material-UI Autocomplete

I am referring to the documentation of React Material-UI (https://material-ui.com/components/autocomplete/).
In the demo code,
<Autocomplete
options={top100Films}
getOptionLabel={(option: FilmOptionType) => option.title}
style={{ width: 300 }}
renderInput={params => (
<TextField {...params} label="Combo box" variant="outlined" fullWidth />
)}
/>
I get how it works, but I am not sure how I am supposed to get the selected value.
For example, I want to use the onChange prop to this so that I can make some actions based on the selection.
I tried adding onChange={v => console.log(v)}
but the v does not show anything related to the selected value.
Solved by using passing in the (event, value) to the onChange props.
<Autocomplete
onChange={(event, value) => console.log(value)} // prints the selected value
renderInput={params => (
<TextField {...params} label="Label" variant="outlined" fullWidth />
)}
/>
The onChange prop works for multiple autocomplete values as well (#Steve Angello #ShwetaJ). The value returned is a list of all the selected options.
const [selectedOptions, setSelectedOptions] = useState([]);
const handleChange = (event, value) => setSelectedOptions(value);
const handleSubmit = () => console.log(selectedOptions);
.
.
.
<Autocomplete
multiple
autoHighlight
id="tags-outlined"
options={top100Films}
getOptionLabel={(option) => option.title}
onChange={handleChange}
filterSelectedOptions
renderInput={(params) => (
<TextField
{...params}
variant="standard"
/>
)}
/>
.
.
.
<button onClick={handleSubmit}>Submit!</button>
You can use useState to store the recevied value and onChange to get the value:
const [selected, setSelected] = useState([]);
return (
<Autocomplete
onChange={(event, value) => setSelected(value)}
renderInput={(params) => <TextField {...params} label="selected" />}
/>
);
Here is TS working example
const tags = ["perimeter", "Algebra", "equation", "square root"];
const handleInput = (e: React.SyntheticEvent, value: string[]) => {
console.log(value);
};
<Autocomplete
multiple
options={tags}
onChange={handleInput}
renderTags={(value: readonly string[], getTagProps) =>
value.map((option: string, index: number) => (
<Chip
variant="outlined"
label={option}
{...getTagProps({ index })}
/>
))
}
renderInput={(params) => (
<TextField
{...params}
variant="filled"
label="Tags"
placeholder="select question tags"
/>
)}
/>
============ Output ===============

Categories