Search code examples
javascriptreactjsreact-bootstrap

How to get select element's value in react-bootstrap?


So I'm trying to get a select element's value in reactjs, but just can't figure it out. The this.refs.selectElement.getDOMNode().value is always coming as undefined. All other controls on the form like text are working fine. Any ideas? Is it that you can't get the value of select element via refs and must use onChange event?

Updated:

var TestSelectClass = React.createClass({
  mixins: [Router.Navigation],

  _handleDube: function(event) {
    DubeActionCreators.DubeTest({
      message: this.refs.message.getDOMNode().value,
      tax: this.refs.tax.getDOMNode().value,
      validity: this.refs.valid_for.getDOMNode().value
    });
  },

  render: function() {
    return (
      <ReactBootstrap.ListGroup>
          <textarea
            className="form-control"
            rows="3"
            placeholder="Enter message"
            ref="message" >
          </textarea>
          <div className="input-group">
            <span className="input-group-addon" id="basic-addon1">$</span>
            <input type="text" className="form-control" placeholder="10" aria-describedby="basic-addon1" ref="tax" />
          </div>
        <Input type="select" value="1" ref="valid_for">
          <option value="1">1 hour</option>
          <option value="2">1 day</option>
          <option value="2">5 days</option>
        </Input>
      </ReactBootstrap.ListGroup>
    )
  }
});

Updated: Solution So, if anyone runs into something similar, apparently if you are using react-bootstrap you can't get to the Input element if you have wrapped it in a ListGroup. Either take it out from it or wrap all Input elements in a <form> tag. This solved my issue, thanks for all the help.


Solution

  • I see you are using react-bootstrap, which includes a wrapper around regular input elements.

    In this case you need to use the getInputDOMNode() wrapper function in order to get the underlying input's actual DOM element. But you can also use the getValue() convenience function that react-bootstrap provides for Input elements.

    So your _handleDube function should look like:

      _handleDube: function(event) {
        DubeActionCreators.DubeTest({
          message: this.refs.message.getInputDOMNode().value,
          tax: this.refs.tax.getInputDOMNode().value,
          validity: this.refs.valid_for.getValue()
        });
      },
    

    See this JSFiddle for a complete example: http://jsfiddle.net/mnhm5j3g/1/