react-bootstrap: clear element value

15,421

Solution 1

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} />
    );
  }
});

Solution 2

For what I'm doing at the moment, I didn't really think it was necessary to control the Input component's value through setState/Flux (aka I didn't want to deal with all the boilerplate)...so here's a gist of what I did. Hopefully the React gods forgive me.

import React from 'react';
import { Button, Input } from 'react-bootstrap';

export class BootstrapForm extends React.Component {

  constructor() {
    super();
    this.clearForm = this.clearForm.bind(this);
    this.handleSave = this.handleSave.bind(this);
  }

  clearForm() {
    const fields = ['firstName', 'lastName', 'email'];
    fields.map(field => {
      this.refs[field].refs['input'].value = '';
    });
  }

  handleSubmit() {
    // Handle submitting the form
  }

  render() {
    return (
      <div>
        <form>
          <div>
            <Input
              ref='firstName'
              type='text'
              label='First Name'
              placeholder='Enter First Name'
            />
            <Input
              ref='lastName'
              type='text'
              label='Last Name'
              placeholder='Enter Last Name'
            />
            <Input
              ref='email'
              type='email'
              label='E-Mail'
              placeholder='Enter Email Address'
            /> 
            <div>
              <Button bsStyle={'success'} onClick={this.handleSubmit}>Submit</Button>
              <Button onClick={this.clearForm}>Clear Form</Button>
            </div>
          </div>
        </form>
      </div>
    );
  }
}

Solution 3

If you use FormControl as an input, and you want to use ref to change/get value from it, you use inputRef instead of ref

<FormControl inputRef={input => this.inputText = input} .../>

and use this to get/change its value:

this.inputText.value

Solution 4

This worked for me in case someone else is looking for an answer :D

You can access the values of react-bootstrap by using

console.log(e.target.form.elements.fooBar.value)

You can clear them by using

e.target.form.elements.fooBar.value = ""
    import React from 'react';
    import {Button, Form} from 'react-bootstrap';

    export default function Example(props) {

    const handleSubmit = (e) => {
    // Handle submitting the form
    }

    const resetSearch = (e) => {
      e.preventDefault();
      e.target.form.elements.fooBar.value = ""
    }

    render() {
      return (
          <Form onSubmit={handleSubmit} onReset={resetSearch} >
             <Form.Control type="input" name="fooBar" />  
             <Button type="submit">  Submit  </Button> 
             <Button onClick={resetSearch} type="submit" > Reset  </Button> 
          </Form>
          );
       }
    }
Share:
15,421
Shikloshi
Author by

Shikloshi

Java software developer for the money. *-Software Developer for fun.

Updated on June 27, 2022

Comments

  • Shikloshi
    Shikloshi almost 2 years

    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?