How to make Material UI Desktop Date Picker lose focus on blur - javascript

I hope you are doing well! I am facing a bit of a problem and I am unable to find a fix for it.
In my website I have 4 DesktopDatePickers (we are using #mui/x-date-picker) and we want to make the Date Picker appear when we click anywhere on the Textfield (not just the calendar icon). So we have the following code:
<Grid item xs={8} md={5} lg={2}>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
label="Creation Date From"
inputFormat="MM/dd/yyyy"
value={dateFrom}
onChange={(newValue) => {
setDateFrom(newValue);
setCreationDateFromOpen(false);
}}
clearable={true}
onClose={() => setCreationDateFromOpen(false)}
open={creationDateFromOpen}
renderInput={(params) => (
<TextField
{...params}
onClick={() => {
setCreationDateFromOpen((open) => !open);
}}
onKeyPress={(e) => {
e.preventDefault();
}}
onKeyDown={(e) => {
if (e.code !== "Backspace") {
e.preventDefault();
}
}}
onChange={(e) => {
e.preventDefault();
}}
fullWidth
id="creationDateFrom"
size="small"
error={false}
/>
)}
/>
</LocalizationProvider>
</Grid>
<Grid item xs={8} md={5} lg={2}>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
label="Creation Date To"
inputFormat="MM/dd/yyyy"
value={dateTo}
onChange={(newValue) => {
setDateTo(newValue);
setCreationdateToOpen(false);
}}
clearable={true}
open={creationDateToOpen}
onClose={() => setCreationdateToOpen(false)}
renderInput={(params) => (
<TextField
{...params}
onClick={() => {
setCreationdateToOpen((open) => !open);
}}
onKeyPress={(e) => {
e.preventDefault();
}}
onKeyDown={(e) => {
if (e.code !== "Backspace") {
e.preventDefault();
}
}}
onChange={(e) => {
e.preventDefault();
}}
fullWidth
size="small"
error={false}
/>
)}
/>
</LocalizationProvider>
</Grid>
<Grid item xs={8} md={5} lg={2}>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
label="Delivery Date From"
inputFormat="MM/dd/yyyy"
value={requestDateFrom}
onChange={(newValue) => {
setRequestDateFrom(newValue);
setModificationDateFromOpen(false);
}}
clearable={true}
open={modificationDateFromOpen}
onClose={() => setModificationDateFromOpen(false)}
renderInput={(params) => (
<TextField
{...params}
onKeyPress={(e) => {
e.preventDefault();
}}
onKeyDown={(e) => {
if (e.code !== "Backspace") {
e.preventDefault();
}
}}
onChange={(e) => {
e.preventDefault();
}}
onClick={() => {
setModificationDateFromOpen((open) => !open);
}}
fullWidth
size="small"
error={false}
/>
)}
/>
</LocalizationProvider>
</Grid>
<Grid item xs={8} md={5} lg={2}>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
label="Delivery Date To"
inputFormat="MM/dd/yyyy"
value={requestDateTo}
onChange={(newValue) => {
setRequestDateTo(newValue);
setModificationDateToOpen(false);
}}
clearable={true}
open={modificationDateToOpen}
onClose={() => setModificationDateToOpen(false)}
renderInput={(params) => (
<TextField
{...params}
onKeyPress={(e) => {
e.preventDefault();
}}
onKeyDown={(e) => {
if (e.code !== "Backspace") {
e.preventDefault();
}
}}
onChange={(e) => {
e.preventDefault();
}}
onClick={() => {
setModificationDateToOpen((open) => !open);
}}
fullWidth
size="small"
error={false}
/>
)}
/>
</LocalizationProvider>
</Grid>
However, We are running through a problem. If a user clicks on one textfield it Focuses then loses focus but displays the Date Picker, but directly after it, they click anywhere and the Date Picker disappears (which is supposed to happen) but the field regains Focus so it looks like the field is awaiting input. So clicking on any other field while the Date Picker is open causes that field to Focus then lose focus and the Browser focuses the Date Field again.
I tried using onFocus={(e)=>e.preventDefault()} in the renderInput TextField but the field still got focused. Using ref.current.blur() gives an error that blur() does not exist.
How can I make the Field not Focus when closing the DatePicker?

Related

How can I keep label not closed in MUI 5 datepicker?

Is there a way to keep Material 5 Datepicker to not close if there's a label but no value?
Currently:
Currently
What I try to get:
Expected
Code:
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
label="Basic example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
I tried to make an own <Box> label above <DatePicker> with styling but I was wondering if there is a cleaner option.
Use InputLabelProps={{ shrink: true }} prop on your TextField component like this:
<DatePicker
label="Basic example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} InputLabelProps={{ shrink: true }} />}
/>

how to show data fetched from api in select mui

I'm trying to show the data, I fetched from Api in select menu. but there seems to be a issue. I'm getting the data, but it's not showing in the select menu. it just shows empty. but I can get the mapped data in console. it just not showing in the select component.
help me figure out. thanks in advance :)
here's my code
export function TransferRBTCard(props) {
const [TransferData, setTransferData] = useState([])
const [ContactValue, setContactValue] = useState('')
const handleChange = (event) => {
setContactValue(event.target.value);
};
const TokenData = () => {
axios.get('http://localhost:8006/api/v2/get/list').then(function (res) {
try {
var result = res.data.data;
console.log(result)
setTransferData(result)
}
catch (error) {
console.log(error)
}
})
}
useEffect(() => {
TokenData()
}, [])]
const handleSubmit = (evnt,) => {
evnt.preventDefault();
axios.post('http://localhost:8006/api/v2/add/transfer')
.then(response => {
if (response.data.success === true) {
alert(response.data.message)
}
})
.catch(error => {
console.log(error.message)
});
}
return (
<Card {...props}>
<CardContent>
<Stack direction="row" alignItems="center" gap={1}>
<ShareOutlinedIcon sx={{ color: "text.secondary" }} />
<Typography sx={{ fontSize: 16, fontWeight: 'bold' }} color="text.secondary" gutterBottom>
Transfer RBT
</Typography>
</Stack>
<Grid>
<FormControl size="small" fullWidth >
<Stack flexDirection='column' gap={1.5} mt={1}>
<InputLabel id="Contact Select" sx={{ mt: 1 }}>Select Contact</InputLabel>
<Select
labelId="Contact Select"
id="demo-simple-select"
value={ContactValue}
label='Select Contact'
onChange={handleChange}
>
{TransferData.map((data) => {
<MenuItem key={data.id} value={data.id}>{data.name}</MenuItem>
})}
</Select>
<TextField
id="filled-hidden-label-small"
label="Receiver" variant="outlined" size="small"
onChange={handleChange}
value={TransferData}
name="Receiver"
inputProps={
{ readOnly: true, }}
className="form-control"
/>
<TextField
id="filled-hidden-label-small" type='number'
label="Amount" variant="outlined" size="small"
onChange={handleChange}
name="Amount"
className="form-control"
/>
<TextField
id="filled-hidden-label-small"
label="Comments" variant="outlined"
multiline
rows={2}
onChange={handleChange}
name="Comments"
className="form-control"
/>
<Button
variant="contained"
type="submit"
onClick={handleSubmit}
sx={{ alignSelf: 'center', backgroundColor: '#000073' }} >Submit</Button>
</Stack>
</FormControl>
</Grid>
</CardContent>
</Card>
);
}
You are not returning from the map function (more correctly, you return undefined by not stating a return).
Change this:
{TransferData.map((data) => {
<MenuItem key={data.id} value={data.id}>{data.name}</MenuItem>
})}
to this:
{TransferData.map((data) => (
<MenuItem key={data.id} value={data.id}>{data.name}</MenuItem>
))}
Note that it is the same as writing:
{TransferData.map((data) => {
return <MenuItem key={data.id} value={data.id}>{data.name}</MenuItem>
})}

ReactJS MaterialUI Modal not refreshing

i have a Modal:
with certain fields, if i open the dropdown and select one of the fields, it does change the state of the Object but doesnt render it in the UI (i reopen the dropdown with the selections so you can see whats behind):
the weird thing about it is, if i do it outside of the Modal, it does work, so it has anything todo with my Modal component?
Here is the BaseModal component:
declare interface IBaseModal {
readonly sx: BaseModalStyle;
readonly body?: React.ReactNode;
readonly isOpen: boolean;
readonly toggleModal: any;
}
const BaseModal: FC<IBaseModal> = ({sx, body, isOpen, toggleModal}: IBaseModal) => (
<Modal open={isOpen} onClose={toggleModal}>
<BaseModalView width={sx.width} height={sx.height}>
{body}
</BaseModalView>
</Modal>
)
then i use it as follows in the view component:
<BaseModal
sx={{width: 800, height: 600}}
isOpen={isModalOpen}
toggleModal={() => setModalOpen(isModalOpen)}
body={modalBody}
/>
const localizer = momentLocalizer(moment);
const [events, setEvents] = useState<CalendarEvent[]>([])
const [schedule, setSchedule] = useState<ISchedule>(initialScheduleEvent);
const [isModalOpen, setModalOpen] = useState<boolean>(false);
const [modalBody, setModalBody] = useState<React.ReactNode | undefined>();
const handleSelectDate = (e: SlotInfo) => {
setModalBody(<Grid container>
<Grid item xs={6}>
<Grid container direction="row" sx={{padding: 2}}>
<Grid item xs={12} sx={{marginBottom: 2}}>
<Typography variant="h5" align='center'>
Schedule your Post
</Typography>
</Grid>
<Grid item xs={12} sx={{marginBottom: 2}}>
<Divider/>
</Grid>
<Grid item xs={12} paddingBottom={3}>
<TextField
style={{marginBottom: 20}}
fullWidth
select
variant="outlined"
label="Plattform"
value={schedule.platform}
onChange={e => setSchedule(prevState => ({...prevState, platform: e.target.value}))}
>
{availableSocialMedias.map(item => (
<MenuItem key={item.socialMedia} value={item.socialMedia}>{item.socialMedia}</MenuItem>
))}
</TextField>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DateTimePicker
renderInput={(props) => <TextField {...props} />}
label="Schedule Date and Time"
value={schedule.schedule.start}
onChange={(e) => {
setSchedule(prevState => ({...prevState, schedule: {
...prevState.schedule, start: e!
}}))
}}
/>
</LocalizationProvider>
<TextField
fullWidth
margin="dense"
multiline
rows="5"
variant="outlined"
label="Post Content"
id="additional-info"
value={schedule.schedule.desc}
onChange={(e) => {
setSchedule(prevState => ({...prevState, schedule: {
...prevState.schedule, desc: e.target.value
}}))
}}
/>
</Grid>
<Grid item xs={12} sx={{width: '100%'}}>
<Stack spacing={2} direction="row" justifyContent='center'>
<Button variant='contained' onClick={() => createEvent()}>Post</Button>
<Button variant='contained' onClick={() => handleCloseModal()}>Close</Button>
</Stack>
</Grid>
</Grid>
</Grid>
<Grid item xs={6} sx={{backgroundColor: '#F7706EFF', justifyContent: 'center'}}>
<img style={{height: 250, width: 400}}
src={"https://web-static.wrike.com/blog/content/uploads/2020/01/Five-Features-of-a-Good-Monthly-Employee-Work-Schedule-Template.jpg?av=718acbc1e2b21264368f12b5cc57c0e2"}/>
<img style={{height: 250, width: 400}}
src={"https://imageio.forbes.com/specials-images/imageserve/605e039657de8844e59d9140/Businesswoman-Planning-Schedule-Using-Calendar-And-Laptop/0x0.jpg?format=jpg&crop=922,615,x0,y0,safe&width=960"}/>
<Typography align='center' variant='h6'>
Schedule for the whole week!
</Typography>
</Grid>
</Grid>)
setModalOpen(true);
}
It also rerenders after i select a certain value in the dropdown for example. but the Modal does not update its value, and i dont get why... i hope for any help.
Small Edit:
After selecting a value and closing / reopening the Modal, the value does change, but why not straight after selecting it but after reopening it?
I fixed the issue having the Body of the Modal, not in a variable but straight in the return body of the component

Unable to use helperText in mui date picker

Here is the code:
<div className={classes.container}>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
fullWidth
inputFormat="dd/MM/yyyy"
// value={registeredDate}
disableFuture
{...props}
helperText="date"
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</div>
I am not seeing the helper text working. Please help
The helperText is the TextField's prop, you can set it like this:
<DesktopDatePicker
fullWidth
inputFormat="dd/MM/yyyy"
disableFuture
{...props}
renderInput={(params) => <TextField helperText="date" {...params} />}
/>

Reactjs: How to pass name, value to Material ui autocomplete?

I am using material ui autocomolete. I want to pass name, value and onchange on autocomplete, the same way we do for TextField. How to do achieve that. ?? My code is not working.
<Autocomplete
id="combo-box-demo"
fullWidth
options={props.propsmaster}
getOptionLabel={(option) => option.abc || option.xyz}
size="small"
renderInput={(params) =>
<TextField
{...params}
label={propsMain.abc}
variant="outlined"
name="name"
onChange={(e) => exhandleChange(e)}
value={values.name}
/>
}
/>
<Autocomplete
id="combo-box-demo"
fullWidth
options={props.propsmaster}
getOptionLabel={(option) => option.abc || option.xyz}
size="small"
name="name"
onChange={(e) => exhandleChange(e)}
value={values.name}
renderInput={(params) =>
<TextField
{...params}
label={propsMain.abc}
variant="outlined"
/>
}
/>

Categories

Resources