Reputation: 422
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?
Upvotes: 5
Views: 16546
Reputation: 5574
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); }
Upvotes: 6
Reputation: 91
In your case, you can also get the input value through this code:
this.inputtext.inputRef.value
Upvotes: 9
Reputation: 3062
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>
);
}
Upvotes: 1