How to pass state data to DesktopDatePicker through renderInput? - reactjs

I'm trying to create a date-picker component but I can't manage to pass the data to the TextField component.
Is there any way to pass the newValue data to TextField through onChange or as a prop through renderInput?
This is my code:
import React from 'react'
import { Input, Box, Typography } from '#mui/material'
import { useField } from 'formik'
import LocalizationProvider from '#mui/lab/LocalizationProvider';
import DesktopDatePicker from '#mui/lab/DesktopDatePicker';
import TextField from '#mui/material/TextField';
import AdapterDateFns from '#mui/lab/AdapterDateFns';
import InputField from '../InputField';
const DateField = ({ label, ...props }) => {
// const [field, meta] = useField(props)
const [value, setValue] = React.useState(new Date('2021-12-25T21:11:54'));
const handleChange = (newValue) => {
setValue(newValue);
console.log(value)
};
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
label="Date desktop"
inputFormat="MM/dd/yyyy"
value={value}
onChange={handleChange}
renderInput={() => <InputField name='date' />}
/>
</LocalizationProvider>
)
}
export default DateField

const [value, setValue] = React.useState(moment('2021-12-25T21:11:54',"YYYY-MM-DD HH:mm:ss"));
or
renderInput={(props) => <InputField {...props} name='date' />}

You can use the renderInput prop in your component as bellow:
return (
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DesktopDatePicker
renderInput={(props) => <TextField {...props} />}
label="Date desktop"
inputFormat="MM/dd/yyyy"
value={value}
onChange={handleChange}
/>
</LocalizationProvider>
)

Related

Not working onChange in react-input-mask (custom input)

Not working onChange in react-input-mask (custom input)
I am not using any libraries as input, but for some reason onChange dont work...
<InputMask
onChange={(e) => console.log(e.target.value)} // dont work...
disabled={true}
>
{(props) => {
return <input type="text" />;
}}
</InputMask>
you need to pass props inside custom input
import React from "react";
import { useState } from "react";
import ReactDOM from "react-dom";
import InputMask from "react-input-mask";
import "./styles.css";
const App = () => {
const [inputValue, setInputValue] = useState("");
const onHandleChange = (event) => {
console.log(event.target.value);
setInputValue(event.target.value);
};
return (
<div className="App">
<h1>react-input-mask with Input from Ant D</h1>
<h2>
Throwing error: react-input-mask: the following props should be passed
to the react-input-mask's component and should not be altered in
children's function: disabled
</h2>
<InputMask mask="99/99/9999" value={inputValue} onChange={onHandleChange}>
{(inputProps) => (
<input {...inputProps} type="tel" className="" disableUnderline />
)}
</InputMask>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Use mui styled for mui-x datepicker

I wanted to customize the datepicker and tried to remove the padding from the input in the mui-x datepicker but nothing was working.
Am i doing something wrong here or is styled not supported by mui-x?
import { styled } from '#mui/material/styles';
import { DesktopDatePicker, LocalizationProvider } from '#mui/x-date-pickers';
import { DatePicker } from '#mui/x-date-pickers/DatePicker';
import { AdapterDateFns } from '#mui/x-date-pickers/AdapterDateFns';
import { TextField } from '#mui/material';
const DateDisplay = styled(DesktopDatePicker)(({ theme }) => ({
'& input':{
padding: 0,
},
}));
return (
<ModalDialog>
<div>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DateDisplay
value={new Date()}
readOnly
onChange={() => {}}
renderInput={(params) => <TextField {...params} />}
></DateDisplay>
</LocalizationProvider>
</div>
</ModalDialog>
);
};
Use sx={{}} prop.
<DateDisplay
value={new Date()}
readOnly
onChange={() => {}}
renderInput={(params) => (
<TextField
{...params}
sx={{
'.MuiInputBase-input': {padding: 0},
}}
/>
)}
></DateDisplay>
With '.MuiInputBase-input' class, you can customize your <TextField> render input for your DatePicker.(You can also see it in the picture)

react - tick logic for material-ui radio button

I have a minimalist function whereby I'm providing two choices in the form of radio inputs: "bull" or "bear".
Full code below:
import React, { useState } from 'react';
import RadioButton from 'material-ui/RadioButton';
const styles = {
rootRadio: {
//left:"37%",
//position:'absolute'
}
}
function RadioComp() {
const [riskP, setRiskP] = useState("bull")
const handleRisk = (e) => {
setRiskP(e.target.value)
}
return (
<React.Fragment>
<h2>Risk profile</h2>
<div>
<span>Bull</span>
<RadioButton
style={styles.rootRadio}
value='bull'
checked={riskP==='bull'}
onChange={handleRisk}
/>
</div>
<div>
<span>Bear</span>
<RadioButton
style={styles.rootRadio}
value='bear'
checked={riskP==='bear'}
onChange={handleRisk}
/>
</div>
</React.Fragment>
)
}
export default RadioComp;
As seen above, I have tried to configure this logic using useState():
const [riskP, setRiskP] = useState("bull")
const handleRisk = (e) => {
setRiskP(e.target.value)
}
However, in the view, clicking on "bear" doesn't do anything. It seems to be locked on "bull."
Question
You have to use RadioGroup with FormControl option.
import React from 'react';
import Radio from '#material-ui/core/Radio';
import RadioGroup from '#material-ui/core/RadioGroup';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import FormControl from '#material-ui/core/FormControl';
import FormLabel from '#material-ui/core/FormLabel';
export default function RadioButtonsGroup() {
const [value, setValue] = React.useState('female');
const handleChange = (event) => {
setValue(event.target.value);
};
return (
<FormControl component="fieldset">
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup name="gender1" value={value} onChange={handleChange}>
<FormControlLabel value="female" control={<Radio />} label="Female" />
<FormControlLabel value="male" control={<Radio />} label="Male" />
<FormControlLabel value="other" control={<Radio />} label="Other" />
</RadioGroup>
</FormControl>
);
}

How to show value, when using date type in TextField?

I am using TextField from material-ui, and I want to show current date in TextField, and also allow user to choose another date. If it is possible?
The value={date} do not appear in the TextField when using type="date". I have tried to find some help on the internet, but can't find anything. Code is below:
Any help is appreciated! And thanks in advance.
import React, { useState } from 'react';
import { TextField } from '#material-ui/core';
import { useForm } from 'react-hook-form';
export const AddDate: React.FC = () => {
const [date, setDate] = useState(
new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear(),
);
// handles when user changes input in date inputfield
const handleChangeDate = (e: React.ChangeEvent<HTMLInputElement>): void => {
setDate(e.target.value);
};
return(
{/*Text field - date*/}
<TextField
name="date"
id="date"
label="Date"
type="date"
InputLabelProps={{ shrink: true }}
inputRef={register}
value={date}
onChange={handleChangeDate}
fullWidth
required
/>
);
};
This works for me.
import React, { useState, useEffect } from "react";
import { TextField } from "#material-ui/core";
import "./styles.css";
import moment from 'moment';
const App =()=> {
const [date, setDate] = useState(
moment(new Date()).format("YYYY-MM-DD")
);
// handles when user changes input in date inputfield
const handleChangeDate = e => {
setDate(e.target.value);
};
console.log(date)
return (
<>
<TextField
name="date"
id="date"
label="Date"
type="date"
InputLabelProps={{ shrink: true }}
value={date}
onChange={handleChangeDate}
fullWidth
required
/>
</>
);
}
export default App;
I just changed your code a little bit. Only change is comming from the useState. You just have to use moment js to convert the date into material-ui date type.
You have to use MuiPickersUtilsProvider. Also, you should need date fomatter moment.js
import DateFnsUtils from '#date-io/date-fns';
import "react-datepicker/dist/react-datepicker.css";
import {
MuiPickersUtilsProvider,
KeyboardDatePicker,
} from '#material-ui/pickers';
import moment from 'moment';
import Input from '#material-ui/core/Input';
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
input={<Input/>}
disableToolbar
variant="inline"
format="yyyy-mm-dd"
margin="normal"
value={value}
onChange={event => {
onValueChange(moment(event).format("YYYY-MM-DD"))
}}
/>
</MuiPickersUtilsProvider>
install dependencies:
npm install #material-ui/pickers#3.2.8
npm install #date-io/date-fns#1.3.13
npm install date-fns#2.8.1

Is it possible to use react-datepicker with react hooks forms?

Is it possible to use react-datepicker with react hooks forms? I tried following sample:
https://codesandbox.io/s/awesome-shape-j0747?fontsize=14&hidenavigation=1&theme=dark
But with no luck.
import React, { useState } from "react";
import "./styles.css";
import { useForm } from "react-hook-form";
import { Row, Col, Form, FormGroup, Label, Input, Button } from "reactstrap";
import DatePicker from "react-datepicker";
export default function App() {
const { register, handleSubmit } = useForm();
const [startDate, setStartDate] = useState();
const [result, setResult] = useState();
const onSearch = event => {
setResult(event);
};
return (
<div className="App">
<Form onSubmit={handleSubmit(onSearch)}>
<Row>
<Col>
<FormGroup>
<Input
type="number"
name="account"
id="account"
placeholder="AccountId"
innerRef={register({ required: true, maxLength: 20 })}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col>
<DatePicker
innerRef={register}
name="datetime"
className={"form-control"}
selected={startDate}
onChange={date => setStartDate(date)}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
timeCaption="time"
dateFormat="MM-dd-yyyy h:mm"
/>
</Col>
</Row>
<Button>Submit</Button>
</Form>
<div>{JSON.stringify(result)}</div>
</div>
);
}
Please take a look at the Controller doc: https://react-hook-form.com/api/#Controller
which we are maintaining a codesandbox example for hosting most the external components UI libs' implementations: https://codesandbox.io/s/react-hook-form-controller-079xx
<Controller
as={ReactDatePicker}
control={control}
valueName="selected" // DateSelect value's name is selected
onChange={([selected]) => selected}
name="ReactDatepicker"
className="input"
placeholderText="Select date"
/>
EDIT
with the latest version of react-hook-form this is the Controller implementation using render:
<Controller
name={name}
control={control}
render={({ onChange, value }) => (
<DatePicker
selected={value}
onChange={onChange}
/>
)}
/>
With react-hooks-form v7
import dependencies:
import { Controller, useForm } from 'react-hook-form'
import DatePicker from 'react-datepicker'
add control to the useForm() hook:
const { control, register, handleSubmit, ... } = useForm()
Add the Controller and DatePicker component:
<Controller
control={control}
name='date-input'
render={({ field }) => (
<DatePicker
placeholderText='Select date'
onChange={(date) => field.onChange(date)}
selected={field.value}
/>
)}
/>

Resources