Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a React Bootstrap textarea form control after the form is submitted?

I have a form made with React Bootstrap to semply submit a string that will be saved on a DB. It works and the submitted message is saved, but I don't know how to clear the textarea when the message is submitted.

As you can see, what I tried to do is to use the useState hook to set an empty value but after the form is submitted the string is still visible in the textarea. Is there any way to do this?

const Form = (props) => {

    const [isLoading, setLoading] = useState(false);
    const [value, setValue] = useState(props.value);

    const handleSubmit = async event => {
        setLoading(true);
        event.preventDefault();

        const res = await fetch(
            // here I call the api
        )
        result = await res.json();
        setValue(null);
        setLoading(false);
    };


    return (
        <Form onSubmit={handleSubmit}>
            <Form.Group className="mb-3" controlId="text">
                <Form.Control as="textarea"
                              required
                              type="text"
                              placeholder=""
                              defaultValue={value}
                />
            </Form.Group>

            <Button
                variant="primary"
                type="submit"
                disabled={isLoading}
            >
                {isLoading ? 'Saving...' : 'Save'}
            </Button>
        </Form>
    )
}

export default Form;
like image 750
user3174311 Avatar asked Oct 27 '25 04:10

user3174311


1 Answers

To my eye, your textarea is currently uncontrolled, and so any changes made to value won't be updated in the Form.Control component.

   <Form.Control 
      as="textarea" 
      rows={3}
      value={value}
      onChange={e => {
         setValue(e.target.value);
      }
   />

Rather than using the defaultValue prop, I would probably use setValue(props.value) to reset value in your handler function.

like image 95
John Detlefs Avatar answered Oct 29 '25 18:10

John Detlefs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!