Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of input text with react-bootstrap

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;
like image 427
Vana Avatar asked Jul 19 '17 15:07

Vana


2 Answers

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!

like image 72
naribo Avatar answered Nov 09 '22 13:11

naribo


Add an Input ref to your form :

<FormControl inputRef={ref => { this.myInput = ref; }} />

so now you get the value like

this.myInput.value
like image 36
Fawaz Avatar answered Nov 09 '22 13:11

Fawaz