Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 749
Proustibat Avatar asked Oct 16 '25 15:10

Proustibat


1 Answers

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();
like image 150
Proustibat Avatar answered Oct 18 '25 18:10

Proustibat



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!