I have react Text Field with defaultValue.In defaultValue, I set the value using props. But I need to set onchage() event to that text field, So then I can update my TextField value. But I can't set them. When I trying to set a value, my default value not showing.
const [openingHours, setOpeningHours] = useState({
monday: '',
});
const mondayHandler = (event) => {
const temp = {...openingHours};
temp.monday = event.target.value;
setOpeningHours(temp);
};
<TextField
type="time"
defaultValue={props.times[0].time1 !== undefined ? props.times[0].time1 : '00:00'}
className={classes.textField}
InputLabelProps={{
shrink: true,
color: 'blue',
}}
InputProps={{
classes: {
underline: classes.underline,
root: classes.timeRoot,
},
}}
/>
How to set Onchange event in to this text field..?
Disclaimer: I am guessing that you are using material-ui's TextField component. If I am wrong, this answer might not hold water.
By using value and onChange to control the state of the TextField you are creating what some people call a "controlled input". The defaultValue prop is meant to be used with uncontrolled inputs, not controlled. Instead, you can set a default value by supplying the correct initial value to useState.
What I'm suggesting would look something like:
const [openingHours, setOpeningHours] = useState({
monday: '00:00',
});
const mondayHandler = (event) => {
const temp = {...openingHours};
temp.monday = event.target.value;
setOpeningHours(temp);
};
<TextField
type="time"
value={openingHours.monday}
onChange={mondayHandler}
...
/>
You will have to verify that 00:00 is a valid value for a TextField with type="time". You might need to supply a Javascript date object instead.