skip to Main Content

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


    1. Maintain a separate state to store the original value of the text input.

    2. Update the input value based on the checkbox state and handle reverting the value back when the checkbox is unchecked.

    import React, { useState } from 'react';
    
    const App = () => {
      const [values, setValues] = useState({ number: '' });
      const [isDevSolution, setIsDevSolution] = useState(false);
      const [originalNumber, setOriginalNumber] = useState('');
    
      const handleCheckboxChange = () => {
        setIsDevSolution(isDevSolution => !isDevSolution);
    
        if (!isDevSolution) {
          // Store the current value as the original value when checkbox is checked
          setOriginalNumber(values.number);
        } 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,
        });
      };
    
      return (
        <form>
          <input
            type='text'
            onChange={handleInputChange}
            label='Number'
            name='number'
            value={isDevSolution ? devSolValue : values.number}
            disabled={isDevSolution}
          />
          <label>
            <input
              type='checkbox'
              onChange={handleCheckboxChange}
              checked={isDevSolution}
            />
            Development Solution
          </label>
        </form>
      );
    };
    export default App;
    

    When the checkbox is checked, we save the current input value into originalNumber. When the checkbox is unchecked, we restore the value from originalNumber back into the values.number field.

    Login or Signup to reply.
  1. 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.

    import "./styles.css";
    import { useState } from "react";
    export default function App() {
      const [value, setValue] = useState({
        checkbox: false,
        input: ""
      });
    
      const handleInputChange = ({ target }) => {
        setValue((prevState) => {
          return { ...prevState, input: target.value };
        });
      };
    
      const handleCheckboxChange = ({ target }) => {
        console.log(target.value);
        setValue((prevState) => {
          return { ...prevState, checkbox: !prevState.checkbox };
        });
      };
    
      return (
        <div className="App">
          <h2>Start editing to see some magic happen!</h2>
          <input
            type="checkbox"
            checked={value.checkbox}
            onChange={handleCheckboxChange}
          />
          <input
            placeholder={"input"}
            name="input"
            value={value.checkbox ? "This is the default value" : value.input}
            disabled={value.checkbox}
            onChange={handleInputChange}
          />
        </div>
      );
    }
    

    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.

    enter image description here

    This is live example

    Edit eager-sutherland-kr9p58

    Hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search