How to get an input value using "refs" in react-bootstrap form? How to get an input value using "refs" in react-bootstrap form? reactjs reactjs

How to get an input value using "refs" in react-bootstrap form?


I just made this issue. My code:

<FormControl    componentClass="input"    placeholder="Enter recipe title"    inputRef={(ref) => {this.input = ref}}    defaultValue={title}/></FormGroup>

And then you can get the value from <FormControl> in some handler like this:

console.log(this.input.value);

Details can be found in my repo: https://github.com/kerf007/recipebook


I have same problem with you, and this is my solution

const FieldGroup = ({id, label, help, inputRef, ...props}) =>  <FormGroup controlId={id}>    <ControlLabel>{label}</ControlLabel>    <FormControl {...props} inputRef={inputRef}/>    {help && <HelpBlock>{help}</HelpBlock>}  </FormGroup>

and my form

<form>    <FieldGroup        id="bookName"        type="text"        label="Name"        placeholder="Enter name..."        inputRef = {(input) => this.inputName = input }     />    <FieldGroup        id="bookAuthor"        label="Author"        type="text"        placeholder="author 's name..."        inputRef={(input) => this.inputAuthor = input}     /></form>

then you can get book 's name and author 's name value by:

this.inputName.value and this.inputAuthor.value


This issue (or more like a change in the way it works) is related to React-Bootstrap. The way you're doing it won't work anymore.

The <FormControl> component directly renders the or other specified component. If you need to access the value of an uncontrolled <FormControl>, attach a ref to it as you would with an uncontrolled input, then call ReactDOM.findDOMNode(ref) to get the DOM node. You can then interact with that node as you would with any other uncontrolled input.

Here's an example:

var React = require('react');var ReactDOM = require('react-dom');var FormControl = require('react-bootstrap').FormControl;React.createClass({  render: function() {    return (<FormControl ref="formControl" />);  },  getFormControlNode: function() {    // Get the underlying <input> DOM element    return ReactDOM.findDOMNode(this.refs.formControl);  }});

As soon as you get the DOM element, you will be able to retrieve the value: this.getFormControlNode().value or do anything else that you want.

PS: Here's a related github issue on this topic.