'How to reset a React-Bootstrap Form after submit?

I added React-Bootstrap to my app. So I change a basic form with React-Bootstrap components.

I can't reset a form after a submit.

Here is my simplified code:

import React from 'react';
import { Form, FormGroup, FormControl, ControlLabel, Button } from 'react-bootstrap';

class MyForm extends React.Component {

    onSubmit( event ) {
        event.preventDefault();
        const textAreaValue = this.textArea.value;
        console.log("textAreaValue : ", textAreaValue);


        // some code here...

        // ERROR HERE (but it works if I 
        // replace bootstrap <Form> 
        // component by a simple <form>
        this.messageForm.reset();
    }

    render() {

        return (
            <Form
                className="form"
                ref={ form => this.messageForm = form }
                onSubmit={ this.onSubmit.bind( this ) }
            >

                <FormGroup controlId="formControlsTextarea">
                    <ControlLabel>My Control Label</ControlLabel>
                    <FormControl
                        required
                        inputRef={ input => this.textArea = input }
                        componentClass="textarea" />
                </FormGroup>

                <Button type="submit">ok</Button>
            </Form>
        );

    }

}
export default MyForm;

I could continue to use a normal then it works but I wonder how to use that one component of React-Boostrap.

Has someone an idea?


The error:

× TypeError: this.messageForm.reset is not a function

When I log this.messageForm it's a React-Bootstrap component. I also tested with inputRef instead of ref but it doesn't work



Solution 1:[1]

By the way I suggest the simplest is to just use simple <form> instead of React-Bootstrap <Form>. And then this.messageForm.reset() works well.

But if for some reasons you need to use Bootstrap Form component, add an id to the form as follows:

        <Form
            id='myForm'
            className="form"
            ref={ form => this.messageForm = form }
            onSubmit={ this.onSubmit.bind( this ) }>
            ...
        </Form>

And in the onSubmit method, access the form element created by React-Bootstrap as follows:

ReactDOM.findDOMNode(this.messageForm).reset();

Solution 2:[2]

Use https://redux-form.com/ to manage your input fields.

This way you have much control with your form fields.

https://codesandbox.io/s/7m0m386m26

Solution 3:[3]

take e for event as a parameter in onSubmit function. then use e.target.reset(); at the end of function. It's work perfectly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 isherwood
Solution 2 Noah John Ucab
Solution 3 Chowdhury Tafsir Ahmed Siddiki