I am working on a form that has a freeform text input field, but if the user checks a box, it will disable the editing the input field and insert a pre-populated text. But if the user unchecks the box, I would like to set the text back to its previous value.
So far, I can disable editing of the input field and get it to display the pre-populated text in the input field, and set it to "values.number", although is seems strange that I have to do it the way that I currently am. But when I uncheck the box, the values is still the pre-populated value, only editable now.
I need a way to save the initial value of the text and insert it back into the text field when the box is unchecked. I have tried storing the text value in state, but it got so overly complicated and wasn’t working so I just blew it out. Can someone please show me what I am doing wrong or how I can make this work the way I am wanting?
—–UPDATED WITH WORKING EXAMPLE——
The Form:
const [values, setValues] = React.useState({} as any);
const [isDevSolution, setIsDevSolution] = React.useState(false);
const [originalNumber, setOriginalNumber] = React.useState('');
const handleCheckboxChange = () => {
setIsDevSolution(isDevSolution => !isDevSolution);
if (!isDevSolution) {
// Store the current value as the original value when checkbox is checked
setOriginalNumber(values.number);
setValues({ ...values, number: 'P0000000' });
} else {
// Restore the original value when checkbox is unchecked
setValues({ ...values, number: originalNumber });
}
};
const handleInputChange = e => {
const { name, value } = e.target;
setValues({
...values,
[name]: ( typeof value === 'string' ? (value).replace(/ +(?= )/g, '').trimStart() : value )
});
};
<Form>
<Input
type='text'
onChange={handleInputChange}
label='Number'
name='number'
value={values.number} // original values from DB
disabled={isDevSolution === true}
/>
<Controls.Checkbox
onChange={handleCheckboxChange}
label='Development Solution'
value={isDevSolution}
/>
</Form>
2
Answers
Maintain a separate state to store the original value of the text input.
Update the input value based on the checkbox state and handle reverting the value back when the checkbox is unchecked.
When the checkbox is checked, we save the current input value into
originalNumber
. When the checkbox is unchecked, we restore the value fromoriginalNumber
back into thevalues.number
field.Unfortuntly I wasn’t able to determine which styling library you are using as there is no much of context provided.
I was able to acheive it using native dom input fields with simple state.
Notice that at the event of clicking on the checkbox we trigger re-render of the
value
state. based on it the new default value would be displayed.This is live example
Hope it helps.