Get value of input text with react-bootstrap

Vana picture Vana · Jul 19, 2017 · Viewed 13.3k times · Source

I try to get value into a input text and add it to a text area with react-bootstrap.

I know I must use ReactDOM.findDOMNode to get value with ref. I don't understand what is wrong.

Here my code :

import React from 'react';
import logo from './logo.svg';
import ReactDOM from 'react-dom';
import { InputGroup, FormGroup, FormControl, Button} from 'react-bootstrap';
import './App.css';
class InputMessages extends React.Component {
constructor(props) { 
super(props);
this.handleChange =      this.handleChange.bind(this); 
    this.GetMessage= this.GetMessage.bind(this); 
this.state = {message: ''};
}   
handleChange(event)
{    
this.setState({message: this.GetMessage.value});
}
GetMessage()
{   
return ReactDOM.findDOMNode(this.refs.message     );
 }
 render() {
    var message = this.state.message;
    return(
 <FormGroup > 
 <FormControl
 componentClass="textarea" value={message} />
 <InputGroup> 
 <FormControl type="text" ref='message' /> 
    <InputGroup.Button>
    <Button bsStyle="primary" onClick={this.handleChange}>Send
    </Button>
    </InputGroup.Button> 
    </InputGroup>
    </FormGroup>
    );
   }
   }  
   export default InputMessages;

Answer

naribo picture naribo · Mar 21, 2019

Form Control has a ref prop, which allows us to use React Refs

Sample Code :

class MyComponent extends React.Component {
  constructor() {
     /* 1. Initialize Ref */
     this.textInput = React.createRef(); 
  }

  handleChange() {
     /* 3. Get Ref Value here (or anywhere in the code!) */
     const value = this.textInput.current.value;
  }

  render() {
    /* 2. Attach Ref to FormControl component */
    return (
      <div>
        <FormControl ref={this.textInput} type="text" onChange={() => this.handleChange()} />
      </div>
    )
  }
}

Hope this helps!