Shikloshi Shikloshi - 1 month ago 22
Javascript Question

react-bootstrap: clear element value

I'm trying to clear my input fields after an

onClick
event.

I'm using
react-bootstrap
library and while there is a
getValue()
method, there is not
setValue(value)
method.

I've stumbled upon this discussion .

I did not fully understand what they are suggesting in order to simply clean a form after submission.

After all, If I would use a simple HTML
<input>
instead of
react-bootstrap
I could grab the node via element
ref
and set it's value to be empty string or something.

What is considered a react way to clean my react-bootstrap
<Input />
element?

Answer

Store the state in your React component, set the element value via props, get the element value via event callbacks. Here is an example:

Here is an example taken directly from their documentation. I just added a clearInput() method to show you you can clear the input by just updating the state of your component. This will trigger a re-render which will cause the input value to update.

const ExampleInput = React.createClass({
  getInitialState() {
    return {
      value: ''
    };
  },

  validationState() {
    let length = this.state.value.length;
    if (length > 10) return 'success';
    else if (length > 5) return 'warning';
    else if (length > 0) return 'error';
  },

  handleChange() {
    // This could also be done using ReactLink:
    // http://facebook.github.io/react/docs/two-way-binding-helpers.html
    this.setState({
      value: this.refs.input.getValue()
    });
  },

  // Example of how you can clear the input by just updating your state
  clearInput() {
    this.setState({ value: "" });
  },

  render() {
    return (
      <Input
        type="text"
        value={this.state.value}
        placeholder="Enter text"
        label="Working example with validation"
        help="Validation is based on string length."
        bsStyle={this.validationState()}
        hasFeedback
        ref="input"
        groupClassName="group-class"
        labelClassName="label-class"
        onChange={this.handleChange} />
    );
  }
});
Comments