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

Taras Yaremkiv picture Taras Yaremkiv · Dec 11, 2016 · Viewed 38.3k times · Source

I'm trying to create a form that appears in modal. So when user input a value, that value is stored in local storage. Here's a picture that help's you to understand what I mean:
enter image description here Here is the code of the form:

function FieldGroup({id, label, help, ...props}) {
    return (
        <ReactBootstrap.FormGroup controlId={id}>
            <ReactBootstrap.ControlLabel>{label}</ReactBootstrap.ControlLabel>
            <ReactBootstrap.FormControl {...props} />
            {help && <ReactBootstrap.HelpBlock>{help}</ReactBootstrap.HelpBlock>}
        </ReactBootstrap.FormGroup>
    );
}

const formInstance = (
    <form>
        <FieldGroup
            id="formControlsText"
            type="text"
            label="Text"
            placeholder="Recipe Name"
            inputRef={ref => { this.input = ref; }}
        />
        <ReactBootstrap.FormGroup controlId="formControlsTextarea">
            <ReactBootstrap.ControlLabel>Ingredients</ReactBootstrap.ControlLabel>
            <ReactBootstrap.FormControl componentClass="textarea" placeholder="Enter Ingredients" />
        </ReactBootstrap.FormGroup>
    </form>
);  

As I've read in bootstrap React tutorial, I should add
<FormControl inputRef={ref => { this.input = ref; }} /> to the FormControl props. But after adding it I get an error when modal form is invoked:

`enter image description here

Answer

Eugene Kulakov picture Eugene Kulakov · Dec 13, 2016

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