5

I've been trying to take inputs from an input field and i used refs(the usual way in react), But it doesn't seem to be working. The input i'm getting is undefined. This is my code:

sendMessage = () => {
   console.log(this.inputtext.value);
}

render(){
   return(
      <div>
         <Input ref={input => this.inputtext = input;} placeholder='message'/>
         <Button onClick={this.sendMessage}>Send</Button>
      </div>
   );
}

I need to take the inputs from the click event of the button. I can't figure out what's wrong. How can i get the input value properly?

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Madushika Perera
  • 402
  • 2
  • 5
  • 13

3 Answers3

9

In your case, you can also get the input value through this code:

this.inputtext.inputRef.value
Sunil Rajput
  • 960
  • 9
  • 19
Sole Valero
  • 91
  • 1
  • 1
6

Since you have used the arrow operator, this.inputtext.value won't work, you need to write:

sendMessage(){
  console.log(this.inputtext.value);
}

In this case semantic-ui's Input Component is a div wrapped on top of input. So you cannot access input element directly through ref. You should use the react's preferred way to get the value, which is

<Input onChange={this.handleMessage.bind(this)} placeholder='message'/>


handleMessage (e) { console.log(e.target.value); }

or without using bind, babel-preset-stage-2 is required for this.

<Input onChange={this.handleMessage} placeholder='message'/>


handleMessage = e => { console.log(e.target.value); }
Vikramaditya
  • 5,444
  • 6
  • 34
  • 45
1

You need to use a normal class method for this to work. You also shouldn't have a semi-colon in the ref.

sendMessage() {
    console.log(this.inputtext.value);
  }

  render(){
     return(
       <div>
        <Input ref={input => this.inputtext = input} placeholder='message'/>
        <Button onClick={this.sendMessage}>Send</Button>
      </div>
   );
  }
spirift
  • 2,994
  • 1
  • 13
  • 18